Whether super
should be at the top or bottom of an __init__
method depends on the use case.
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.