Python Create a Class with Multiple Inheritance
In Python, multiple inheritance means a class can inherit from multiple parent classes. Through multiple inheritance, a subclass can inherit attributes and methods from multiple parent classes. Below is a simple example showing how to create a class with multiple inheritance.
Example
class Parent1:
def method1(self):
print("This is method1 from Parent1")
class Parent2:
def method2(self):
print("This is method2 from Parent2")
class Child(Parent1, Parent2):
def method3(self):
print("This is method3 from Child")
# Create an instance of the Child class
child = Child()
# Call the method inherited from Parent1
child.method1()
# Call the method inherited from Parent2
child.method2()
# Call Child's own method
child.method3()
def method1(self):
print("This is method1 from Parent1")
class Parent2:
def method2(self):
print("This is method2 from Parent2")
class Child(Parent1, Parent2):
def method3(self):
print("This is method3 from Child")
# Create an instance of the Child class
child = Child()
# Call the method inherited from Parent1
child.method1()
# Call the method inherited from Parent2
child.method2()
# Call Child's own method
child.method3()
Code explanation:
Parent1andParent2are two parent classes, which definemethod1andmethod2methods.Childclass inheritsParent1andParent2, and defines its ownmethod3methods.- In
ChildIn the instance of the class, you can callParent1andParent2's methods, and also callChildthe class's own methods.
Output result:
This is method1 from Parent1 This is method2 from Parent2 This is method3 from ChildOther extensions
Python3 Examples