Python Inheritance OOPS - (Multiple and Multilevel Inheritance)
What is Inheritance in Python OOPS?
Inheritance is a technique for generating a new class that uses the information of an existing one without changing it. A derived class is the freshly produced class (or child class). The existing class is also a basic class (or parent class).
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Output
Multiple Inheritance in Python
Numerous inheritance refers to when a class is derived from multiple base classes. The base case's characteristics are passed down to the derived class.
Syntax:
Class Base1:
Body of the class
Class Base2:
Body of the class
Class Derived(Base1, Base2):
Body of the class
Example:
Python Program to depict multiple inheritance
class Class1:
def m(self):
print("In Class1")
class Class2(Class1):
def m(self):
print("In Class2")
class Class3(Class1):
def m(self):
print("In Class3")
class Class4(Class2, Class3):
def m(self):
print("In Class4")
Class2.m(self)
Class3.m(self)
Class1.m(self)
obj = Class4()
obj.m()
Output:
Multilevel Inheritance in Python
A derived class can also be inherited. Python multilevel inheritance is the term for this. In Python, it can be of any depth. The characteristics of the base class and the derived class are inherited into the new derived class in multilevel inheritance.
An example with the corresponding visualization is given below.
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass