Inheritance is the most important aspect of object-oriented programming which simulates the real world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class.
It provides re-usability of the code.
Example 1:
#!/usr/bin/python3classParent:# define parent class parentAttr =100def__init__(self):print ("Calling parent constructor")defparentMethod(self):print ('Calling parent method')defsetAttr(self,attr): Parent.parentAttr = attrdefgetAttr(self):print ("Parent attribute :", Parent.parentAttr)classChild(Parent):# define child classdef__init__(self):print ("Calling child constructor")defchildMethod(self):print ('Calling child method')c =Child()# instance of childc.childMethod()# child calls its methodc.parentMethod()# calls parent's methodc.setAttr(200)# again call parent's methodc.getAttr()# again call parent's method
Output:
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
Example 2:
dog barking
Animal Speaking
Multi Level Inheritance:
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-level inheritance is archived when a derived class inherits another derived class. There is no limit on the number of levels up to which, the multi-level inheritance is archived in python.
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()