There are two main ways for a derived class to call a base class's methods.
Base.method(self):
class Derived(Base):
def method(self):
Base.method(self)
...
or super().method():
class Derived(Base):
def method(self):
super().method()
...
Suppose I now do this:
obj = Derived()
obj.method()
As far as I know, both Base.method(self)
and super().method()
do the same thing. Both will call Base.method
with a reference to obj
. In particular, super()
doesn't do the legwork to instantiate an object of type Base
. Instead, it creates a new object of type super
and grafts the instance attributes from obj
onto it, then it dynamically looks up the right attribute from Base
when you try to get it from the super object.
The super()
method has the advantage of minimizing the work you need to do when you change the base for a derived class. On the other hand, Base.method
uses less magic and may be simpler and clearer when a class inherits from multiple base classes.
Most of the discussions I've seen recommend calling super()
, but is this an established standard among Python coders? Or are both of these methods widely used in practice? For example, answers to this stackoverflow question go both ways, but generally use the super()
method. On the other hand, the Python textbook I am teaching from this semester only shows the Base.method
approach.