Inheritance enable us to define a class that takes all the functionality from parent class and allows us to add more. In this article, you will learn to use inheritance in Python.
It refers to defining a new class with little or no modification to an existing class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.
classPolygon:def__init__(self,no_of_sides): self.n = no_of_sides self.sides = [4for i inrange(no_of_sides)]definputSides(self): self.sides = [float(input("Enter side "+str(i+1)+" : "))for i inrange(self.n)]defdispSides(self):for i inrange(self.n):print("Side",i+1,"is",self.sides[i])classTriangle(Polygon):def__init__(self):#super().__init__(3) Polygon.__init__(self,3)deffindArea(self): a, b, c = self.sides# calculate the semi-perimeterprint(a,b,c) s = (a + b + c) /2 area = (s*(s-a)*(s-b)*(s-c)) **0.5print('The area of the triangle is %0.2f'%area)t =Triangle()t.inputSides()t.dispSides()t.findArea()
Enter side 1 : 5
Enter side 2 : 6
Enter side 3 : 5
Side 1 is 5.0
Side 2 is 6.0
Side 3 is 5.0
5.0 6.0 5.0
The area of the triangle is 12.00
Method Overriding
In the above example, notice that __init__() method was defined in both classes, Triangle as well Polygon. When this happens, the method in the derived class overrides that in the base class. This is to say, __init__() in Triangle gets preference over the same in Polygon.
Generally when overriding a base method, we tend to extend the definition rather than simply replace it. The same is being done by calling the method in base class from the one in derived class (calling Polygon.__init__() from __init__() in Triangle).
A better option would be to use the built-in function super(). So, super().__init__(3) is equivalent to Polygon.__init__(self,3) and is preferred. You can learn more about the super() function in Python.
Two built-in functions isinstance() and issubclass() are used to check inheritances. Function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each and every class in Python inherits from the base class object.
# Parent classclassDog:# Class attribute species ='mammal'# Initializer / Instance attributesdef__init__(self,name,age): self.name = name self.age = age# instance methoddefdescription(self):return"{} is {} years old".format(self.name, self.age)# instance methoddefspeak(self,sound):return"{} says {}".format(self.name, sound)# Child class (inherits from Dog class)classRussellTerrier(Dog):defrun(self,speed):return"{} runs {}".format(self.name, speed)# Child class (inherits from Dog class)classBulldog(Dog):def__init__(self,n1,a1): self.n1 = n1 self.a1 = a1print ("Dog name is {} and age is {}".format(self.n1,self.a1))defrun(self,speed):return"{} runs {}".format(self.n1, speed)# Child classes inherit attributes and# behaviors from the parent classjim =Bulldog("Jim", 12)#print(jim.description())# Child classes have specific attributes# and behaviors as wellprint(jim.run("slowly"))
Dog name is Jim and age is 12
Jim runs slowly
Example -2:
# Parent classclassDog:# Class attribute species ='mammal'# Initializer / Instance attributesdef__init__(self,name,age): self.name = name self.age = age# instance methoddefdescription(self):return"{} is {} years old".format(self.name, self.age)# instance methoddefspeak(self,sound):return"{} says {}".format(self.name, sound)# Child class (inherits from Dog() class)classRussellTerrier(Dog):defrun(self,speed):return"{} runs {}".format(self.name, speed)# Child class (inherits from Dog() class)classBulldog(Dog):defrun(self,speed):return"{} runs {}".format(self.name, speed)# Child classes inherit attributes and# behaviors from the parent classjim =Bulldog("Jim", 12)print(jim.description())# Child classes have specific attributes# and behaviors as wellprint(jim.run("slowly"))# Is jim an instance of Dog()?print(isinstance(jim, Dog))# Is julie an instance of Dog()?julie =Dog("Julie", 100)print(isinstance(julie, Dog))# Is johnny walker an instance of Bulldog()johnnywalker =RussellTerrier("Johnny Walker", 4)print(isinstance(johnnywalker, Bulldog))# Is julie and instance of jim?print(isinstance(julie, jim))
Jim is 12 years old
Jim runs slowly
True
True
False
TypeError Traceback (most recent call last)
<ipython-input-69-c976ae4d1a2c> in <module>
52
53 # Is julie and instance of jim?
---> 54 print(isinstance(julie, jim))
TypeError: isinstance() arg 2 must be a type or tuple of types
Example - 3 :
classDog: species ='mammal'classSomeBreed(Dog):passclassSomeOtherBreed(Dog): species ='reptile'frank =SomeBreed()print(frank.species)beans =SomeOtherBreed()print(beans.species)print(frank.species)
mammal
reptile
mammal
Method Resolution Order in Python
Every class in Python is derived from the class object. It is the most base type in Python.
So technically, all other class, either built-in (int, string,list,etc) or user-defines, are derived classes and all objects are instances of object class.