Name: Tawheed pasha Subject code:21EC643
USN: 1EP21EC104 Class: 6th (B sec)
Inheritance in Python
One of the core concepts in object-oriented programming (OOP) languages is inheritance. It
is a mechanism that allows you to create a hierarchy of classes that share a set of properties
and methods by deriving a class from another class. Inheritance is the capability of one class
to derive or inherit the properties from another class
Types of Inheritance in Python
Types of Inheritance depend upon the number of child and parent
classes involved. There are four types of inheritance in Python:
Single Inheritance:
Single inheritance enables a derived class to inherit properties from a single parent class, thus
enabling code reusability and the addition on of new features to existing code.
Example:
# Python program to demonstrate
# single inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
Multiple Inheritance:
When a class can be derived from more than one base class this type of inheritance is called
multiple inheritances. In multiple inheritances, all the features of the base classes are
inherited into the derived class.
Example:
class Mother:
mothername = ""
def mother(self):
print([Link])
class Father:
fathername = ""
def father(self):
print([Link])
class Son(Mother, Father):
def parents(self):
print("Father :", [Link])
print("Mother :", [Link])
s1 = Son()
[Link] = "RAM"
[Link] = "SITA"
[Link]()
Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class are further inherited
into the new derived class. This is similar to a relationship representing a child and a
grandfather.
Example:
class Grandfather:
def __init__(self, grandfathername):
[Link] = grandfathername
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
[Link] = fathername
Grandfather.__init__(self, grandfathername)
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
[Link] = sonname
Father.__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', [Link])
print("Father name :", [Link])
print("Son name :", [Link])
s1 = Son('Prince', 'Rampal', 'Lal mani')
print([Link])
s1.print_name()
Hierarchical Inheritance:
When more than one derived class are created from a single base this type of inheritance is
called hierarchical inheritance. In this program, we have a parent (base) class and two child
(derived) classes.
Example:
class Parent:
def func1(self):
print("This function is in parent class.")
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()