Inheritance is concept where one class accesses the methods and properties of another class.
- Parent class is the class being inherited from, also called base class.
- Child class is the class that inherits from another class, also called derived class.
There are two types of inheritance in python −
- Multiple Inheritance
- Multilevel Inheritance
Multiple Inheritance −
In multiple inheritance one child class can inherit multiple parent classes.
Example
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Daughter(Father, Mother):
def parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()Output
Father : Srinivas Mother : Anjali
Multilevel Inheritance
In this type of inheritance, a class can inherit from a child class/derived class.
Example
#Daughter class inherited from Father and Mother classes which derived from Family class.
class Family:
def family(self):
print("This is My family:")
class Father(Family):
fathername = ""
def father(self):
print(self.fathername)
class Mother(Family):
mothername = ""
def mother(self):
print(self.mothername)
class Daughter(Father, Mother):
def parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Daughter()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.family()
s1.parent()Output
This is My family: Father : Srinivas Mother : Anjali