Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a variable in a superclass, but don't overwrite inheritor's setting

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading