I’d like to have a superclass that, as part of it’s interface, provides a variable (or a getter function), and allows (but does not require) an inheritor to set this value. As follows:
class A(object):
def __init__(self):
self._value = DEFAULT_VALUE
def value(self):
return self._value
class B(A):
def __init__(self, value):
self._value = value
super().__init__()
class C(A):
def __init__(self):
#note this class does not care about setting value
super.__init__()
However, super’s init will overwrite any custom setting done by B. If I don’t set it in the superclass, and then a subclass does not want to implement it, anything that uses that variable will fail.
How do I create this variable in the superclass without overwriting what a subclass may want to set it to?
>Solution :
As mentioned in the comments, you can simply do your subclass-specific initialization after calling super().__init__:
class B(A):
def __init__(self, value):
super().__init__()
# time to overwrite that default value
self._value = value
You can also just not call super().__init__ if not necessary:
class B(A):
def __init__(self, value = None):
if value is None:
# fallback to default
super().__init__()
else:
# otherwise set value from caller
self._value = value
b = B()
print(b.value()) # prints the default value
b = B("overridden value")
print(b.value()) # prints "overridden value"