Python

champak
₹2,000.00 ₹1,500.00
The Python Programming Language at Champak's World
  • 15 students
  • 22 lessons
  • 0 quizzes
  • 10 week duration

Python

How to implement Multiple Inheritance in Python

Python supports multiple inheritance where one class is derived from more than one class. It is useful in cases where we need to get the features of more than one class.

Here is a very simple example.


class A:
def __init__(self,a):
self.a=a
def __str__(self):
return "A={0}".format(self.a)

class B:
def __init__(self,b):
self.b=b
def __str__(self):
return "B={0}".format(self.b)
class C(A,B):
def __init__(self,a,b):
A.__init__(self,a)
B.__init__(self,b)
def __str__(self):
return "{0},{1}".format(A.__str__(self),B.__str__(self))

x=C(1,2)
print(x)

Output
A=1,B=2

 

What happens if there are more than one members with the same signature in two base classes. Python picks the first one directly. If you want the second you have to typecast.


class A:
def __init__(self,a):
self.a=a
def __str__(self):
return "A={0}".format(self.a)
def f(self):
print("Hello from A")
class B:
def __init__(self,b):
self.b=b
def __str__(self):
return "B={0}".format(self.b)
def f(self):
print("Hello from B")
class C(A,B):
def __init__(self,a,b):
A.__init__(self,a)
B.__init__(self,b)
def __str__(self):
return "{0},{1}".format(A.__str__(self),B.__str__(self))

x=C(1,2)
print(x)
x.f()
B(x).f()

Output
A=1,B=2
Hello from A
Hello from B

end

Leave a Reply

Your email address will not be published. Required fields are marked *