English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Inheritance allows us to define a class that inherits all the functionalities of the parent class and allows us to add more functionalities. In this article, you will learn how to use inheritance in Python.
Inheritance is a powerful feature in object-oriented programming.
It refers to defining a newclass, which is rarely or not modified from the existing class. The new class is calledDerived (or child) class, and the new class that inherits from it is calledBase (or parent) class.
class BaseClass: # Body of the base class class DerivedClass(BaseClass): # Body of the derived class
Derived classes inherit elements from the base class and add new elements to it. This can improve the reusability of the code.
To demonstrate the use of inheritance, let's take an example.
A polygon is a shape with3A closed figure with one or more edges. Let's say we have a class named Polygon, which is defined as follows.
class Polygon: def __init__(self, no_of_sides): self.n = no_of_sides self.sides = [0 for i in range(no_of_sides)] def inputSides(self): self.sides = [float(input("Input sides "+str(i+1)+" : ")) for i in range(self.n)] def dispSides(self): for i in range(self.n): print("sides",i+1,"is",self.sides[i])
This class has data attributes used to store the number of sides, sidesnumberand the size of each side as a list, i.e.number of sides.
The method inputSides() takes the size of each side, similarly, dispSides() displays them correctly.
A triangle is a polygon with3an n-sided polygon. Therefore, we can create a class named Triangle that inherits from Polygon. This makes all available properties in Polygon easily usable in Triangle. We do not need to redefine them (code reusability). Triangle is defined as follows.
class Triangle(Polygon): def __init__(self): Polygon.__init__(self,3) def findArea(self): a, b, c = self.sides # Calculate the semi-perimeter s = (a + b + c) / 2 area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f'%area)
However, the class Triangle has a new method findArea() to find and print the area of the triangle. This is an example of the execution.
>>> t = Triangle() >>> t.inputSides() Input sides 1 : 3 Input sides 2 : 5 Input sides 3 : 4 >>> t.dispSides() sides 1 is 3.0 sides 2 is 5.0 sides 3 is 4.0 >>> t.findArea() The area of the triangle is 6.00
We can see that although we have not defined methods such as inputSides() or sides() for the class Triangle, we can still use them.
If the property is not found in the class, the search continues to the base class. If the base class itself is derived from another class, the operation will be repeated recursively.
In the above example, please note that the __init__() method is defined in both the Triangle and Polygon classes. When this happens, the method in the derived class overrides the method in the base class. That is, Triangle.__init__() takes precedence over Polygon.__init__().
Generally, when overriding basic methods, we tend to extend the definition rather than simply replacing it. This is achieved by calling the method from the base class in the derived class (calling Polygon.__init__() from Triangle.__init__()).
The better choice is to use the built-in function super(). Therefore, super().__init__(3) is equivalent to Polygon.__init__(self,3) and is the preferred choice. You can learn more aboutIn Python'ssuper() function'sMore information.
The two built-in functions isinstance() and issubclass() are used to check inheritance. If the object is an instance of the class or any other class derived from it, the function isinstance() returns True. Every class in Python inherits from the base class object.
>>> isinstance(t, Triangle) True >>> isinstance(t, Polygon) True >>> isinstance(t, int) False >>> isinstance(t, object) True
Similarly, issubclass() is used to check inheritance.
>>> issubclass(Polygon, Triangle) False >>> issubclass(Triangle, Polygon) True >>> issubclass(bool, int) True