Inheritance in Python
Inheritance in Python:
Inheritance in Python is the capability of one class to derive or inherit the properties from another class. In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class.
Example:
- Class A:
//pass
Class B(A):
//pass
Benefits of Inheritance:
- Reusability of code.
- We can use the features of the other class, without modifying it.
- It is transitive in nature i.e. A->B->C == A->C and B->C.
Syntax:
class Parentclass_name:
##statement
class child_class(Parentclass_name):
##statement
Different forms of Inheritance:
- Single inheritance: When a child class inherits from only one parent class, it is called single inheritance.
Code #1:
#python Program
#Rishikesh
#singel level inheritence
# Creating a PrepInsta class
class PrepInsta:
def __init__(self,a):
self.a =a
print(self.a)
# Creating a Prepster class
class Prepster(PrepInsta):
def __init__(self,a):
# Calling constructor of
# PrepInsta class
PrepInsta.__init__(self,a)
obj1 = Prepster(5)
- Multiple inheritance: When a child class inherits from multiple parent classes, it is called multiple inheritance
Code #2:
#python Program
#Rishikesh
#multiple inheritence
class A(object):
def __init__(self):
self.str1 = “PrepInsta”
print(“A”)
class B(object):
def __init__(self):
self.str2 = “Prepster”
print(“B”)
class C(A, B):
def __init__(self):
# Calling constructors of A
# and B classes
A.__init__(self)
B.__init__(self)
print(“C”)
def printStrs(self):
print(self.str1, self.str2)
ob = C()
ob.printStrs()
Output:
A
B
C
PrepInsta Prepster
- Multilevel inheritance: When we have a child and grandchild type relationship.
Code #3
#python Program
#Rishikesh
#multilevel inheritence
class A(object):
def __init__(self):
self.str1 = “PrepInsta”
print(“A”)
class B(A):
def __init__(self):
self.str2 = “Prepster”
A.__init__(self)
print(“B”)
class C(B):
def __init__(self):
# Calling constructors of A
# and B classes
B.__init__(self)
print(“C”)
def printStrs(self):
print(self.str1, self.str2)
ob = C()
ob.printStrs()
Output:
A
B
C
PrepInsta Prepster
- Hierarchical inheritance More than one derived classes are created from a single parent.
- Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a mixture of more than one type of inheritance.
Login/Signup to comment