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
self
self, which is mostly used as the first parameter of instance methods of classes, always represents the calling object/instance of the class.
super()
super() refers to object of parent class. It is useful in case of method overriding and this is in case of numerous programming languages including C++, Java etc. In Java, super() is used to call the constructor of parent class.
Please have a look at the below little example.
class TopClass(object):
def __init__(self, name, age):
self.name = name;
self.age = age;
def print_details(self):
print("Details:-")
print("Name: ", self.name)
print("Age: ", self.age)
self.method()
def method(self):
print("Inside method of TopClass")
class BottomClass(TopClass):
def method(self):
print("Inside method of BottomClass")
def self_caller(self):
self.method()
def super_caller(self):
parent = super()
print(parent)
parent.method()
child = BottomClass ("Ryan Holding", 26)
child.print_details()
"""
Details:-
Name: Ryan Holding
Age: 26
Inside method of BottomClass
"""
parent = TopClass("Rishikesh Agrawani", 26)
parent.print_details()
"""
Details:-
Name: Rishikesh Agrawani
Age: 26
Inside method of TopClass
"""
child.self_caller()
child.super_caller()
"""
Inside method of BottomClass
<super: <class 'BottomClass'>, <BottomClass object>>
Inside method of TopClass
"""