Home > Back-end >  Create a variable in a superclass, but don't overwrite inheritor's setting
Create a variable in a superclass, but don't overwrite inheritor's setting

Time:01-07

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?

CodePudding user response:

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"

CodePudding user response:

Edit: Updated according to Simon Hawe's comment

You could do something like this:

class A(object):
    def __init__(self, value=DEFAULT_VALUE):
        self._value = value

    def value(self):
        return self._value

class B(A):
    def __init__(self, value):
        super().__init__(value)

Now _value will only be the default value if a subclass did not provide a value to the super().__init__() call.

  •  Tags:  
  • Related