Я бы подумал о том, чтобы сделать x
свойством.
class Base():
def __init__(self):
self.__x = None
self.__x_is_set = False
@property
def x(self):
if not self.__x_is_set:
raise NotImplementedError('Descendents from Base must set x')
else:
return self.__x
@x.setter
def x(self, value):
self.__x = value
self.__x_is_set = True
class GoodSub(Base):
def __init__(self):
super().__init__()
self.x = 5
class BadSub(Base):
def __init__(self):
super().__init__()
pass
class AlsoBad(Base):
def __init__(self):
super().__init__()
self.__x = 5 # sets the attribute, but not through the property
>>> g, a, b = GoodSub(), BadSub(), AlsoBad()
>>> g.x
5
>>> a.x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in x
NotImplementedError: Descendents from Base must set x
>>> b.x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in x
NotImplementedError: Descendents from Base must set x