How does Python's super() work with multiple inheritance?
In Python, super()
is used to call a method from a parent class. When used with multiple inheritance, it is important to specify the parent class from which the method should be called. This can be done by passing in the parent class as an argument to super()
. For example:
class Parent1:
def method(self):
print("Parent1 method")
class Parent2:
def method(self):
print("Parent2 method")
class Child(Parent1, Parent2):
def method(self):
super(Parent1, self).method()
super(Parent2, self).method()
c = Child()
c.method()
Watch a video course
Python - The Practical Guide
This will output:
Parent1 method Parent2 method
It is calling parent1 method using super(Parent1, self).method() and parent2 method using super(Parent2, self).method()
In python version 3.x, if you don't pass any argument while calling super() it will automatically pass the current class and its parent class, it will look for the method in the parent class and if not found will look in the next parent class and so on.