Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an __init__ automatically execute code after calling super?

Tags:

python

I have something like this:

class SuperClass(object):
    def __init__(self):
        # initialization stuff

    def always_do_this_last(self):
        # cleanup stuff


class SubClass(SuperClass):
    def __init__(self):
        super().__init__()
        # intermediate stuff
        self.always_do_this_last()

Is it possible to automatically call that last line? Every subclass of SuperClass needs perform the cleanup.

like image 990
Chuck Avatar asked Mar 24 '26 04:03

Chuck


2 Answers

Instead of overriding __init__, define a method that SuperClass.__init__ will call.

class SuperClass(object):
    def __init__(self):
        # do some stuff
        self.child_init()
        self.cleanup()

    def cleanup():
        ...

    def child_init(self):
        pass


class SubClass(SuperClass):
    def child_init(self):
        ...

You can define SuperClass.__init_subclass__ to ensure child_init is overriden, or use the abc module to make SuperClass.child_init an abstract method

like image 175
chepner Avatar answered Mar 26 '26 16:03

chepner


One option could be to use a method that the subclasses could override without overriding __init__(). Maybe like this:

class SuperClass:
    def __init__(self):
        # initialization stuff
        self.setup_subclass()
        self.always_do_this_last()

    def setup_subclass(self):
        pass

    def always_do_this_last(self):
        # cleanup stuff

class SubClass(SuperClass):
    def setup_subclass(self):
        # intermediate stuff

Would that work for you?

like image 29
Ralf Avatar answered Mar 26 '26 16:03

Ralf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!