What\'s the difference between using super().method()
and self.method()
, when we inherit something from a parent class and why use one instead of anoth
super().method()
will call the parent classes implementation of method
, even if the child has defined their own. You can read the documentation for super for a more in-depth explanation.
class Parent:
def foo(self):
print("Parent implementation")
class Child(Parent):
def foo(self):
print("Child implementation")
def parent(self):
super().foo()
def child(self):
self.foo()
c = Child()
c.parent()
# Parent implementation
c.child()
# Child implementation
For singular-inheritance classes like Child
, super().foo()
is the same as the more explicit Parent.foo(self)
. In cases of multiple inheritance, super
will determine which foo
definition to use based on the Method Resolution Order, or MRO.
A further motivating example: which method gets called if we subclass Child
and write another implementation of foo
?
class Grandchild(Child):
def foo(self):
print("Grandchild implementation")
g = Grandchild()
g.parent()
# Parent implementation
g.child()
# Grandchild implementation