Notification texts go here Contact Us Buy Now!

Should super always be at the top of an __init__ method, or can it be at the bottom?

Whether super should be at the top or bottom of an __init__ method depends on the use case.

Consider this example:

class Foo():
    def __init__(self):
        print(self.name)

    @property
    def name(self):
        return self.__class__.__name__


class Bar(Foo):
    def __init__(self, name):
        self.name = name
        super().__init__()

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name):
        self.__name = name

If you invoked super() before setting self.name within Bar.__init__, you'd get an AttributeError because the required name has not yet been set.

Is it bad form to have it at the bottom of an init method?

This question is irrelevant. Whether it's considered bad form or not, there are valid use cases for moving the superclass initialization to the bottom of a subclass's constructor. The placement of the super call should be based on the implementation of the superclass constructor, not on style.

For example, consider a superclass where, upon construction, an attribute's value depends on an attribute of the subclass. In such a case, the Superclass can't be initialized until the subclass_attr attribute is given to the subclasses.

class Superclass:
    def __init__(self):
        if self.subclass_attr:
            self.attr = 1
        else:
            self.attr = 2

Therefore, the call to super must be placed at the bottom of the subclass's constructor.

class Subclass(Superclass):
    def __init__(self):
        self.subclass_attr = True
        super(Superclass, self).__init__()

Ultimately, the decision of where to place super should be based on necessity, not style.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.