Search code examples
pythonpython-3.xabstract-classderived-class

Different behavior in base class __init__ depending on derived class


I have an abstract class Base containing a member boolean do_thing which will either trigger a one-time action on start-up, or do nothing. This variable can be overridden by a derived class Derived, but doing a super().__init__() call at the beginning of the Derived's __init__ leads to the one-time action being always based on what do_thing is set to in Base.

I only see two options for getting around this, neither of which seem ideal to me:

  1. Call super().__init__() at the end of every derived class's __init__ rather than the beginning, which means I can't rely on other default variables set in Base.

  2. Explicitly call the one-time action at the end of every derived class's __init__, which means either duplicated code, or an extra function in Base that will only ever be called at startup.

Some example code

from abc import ABC

class Base(ABC):
    def __init__(self):
        self.do_thing = False

        # Want to wait for child class init before running this
        if self.do_thing:
            configuration.set(do_thing_parameters) 


class Derived(Base):
    def __init__(self):
        super().__init__()
        # Should have configs properly set based on this being true
        self.do_thing = True

class RegularDerived(Base):
    def __init__(self):
        super().__init__()
        # Don't modify the config

Is there a better way of doing this that I'm missing?


Solution

  • Try setting the "do_thing" variable as a default parameter, as shown below...

    from abc import ABC
    
    class Base(ABC):
        def __init__(self, do_thing=False):
            if do_thing:
                configuration.set(do_thing_parameters) 
    
    
    class Derived(Base):
        def __init__(self):
            super().__init__(True)