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 another?
The only thing that comes to my mind is that with static methods it becomes obviously impossible to call self.method(). As for everything else I can't come up with justification to use super().
Could someone present a dummy example when choosing one over another matters and explain why, or is it just convention thing?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With