Python Inheritance
Contents
What is inheritance in Python?
The process of deriving existing information from a parent class and using the new class to perform some extra functionalities is known as an inheritance in a programming language. It provides the code reusability feature as we do not need to create a class from scratch every time if we already created it before.
The class that is acquiring the properties from another class is known as derived class whereas the parent class providing the features is known as a base class.
The syntax for inheriting any class in Python is as below:
class devivedClassName (ParentClass1[, ParentClass2, …]):
class_suite
class Parent: # define parent class parentAttr = 100 def __init__(self): print("Calling parent constructor") def parentMethod(self): print('Calling parent method') def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print("Parent attribute :", Parent.parentAttr) class Child(Parent): # define child class def __init__(self): print("Calling child constructor") def childMethod(self): print('Calling child method') c = Child() # instance of child c.childMethod() # child calls its method c.parentMethod() # calls parent's method c.setAttr(200) # again call parent's method c.getAttr() # again call parent's method
The output of the site is:-
Calling child method
Calling parent method
Parent attribute : 200
What are methods available for inheritance in Python?
What are Python Multiple inheritances?
Like C++, a class can be derived from more than one base classes in Python. This is called multiple inheritances.
In multiple inheritances, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritances is similar to single inheritance.
The syntax for the multiple inheritances is
class Base2:
class MultiDerived(Base1, Base2):
What is Python Multi-Level inheritance?
The process of inheriting further from derived class is called multi-level inheritance.
class Base1:
class Base2:
class MultiDerived(Base1, Base2):