Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between super().method() and self.method()

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?

like image 892
Afterlook Avatar asked Oct 29 '25 19:10

Afterlook


1 Answers

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
like image 86
Patrick Haugh Avatar answered Nov 01 '25 10:11

Patrick Haugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!