Inheritance in Python
In Python programming, the concept of “Inheritance” enables us to define a new class that acquires all the functionality from an existing class and allows us to add more attribute(s) or method(s). The new class is called the Child (or derived) class and the existing one from which it is inherited is called the Parent (or base) class.
Basically it provides re-usability of the code. We don’t have to write the same code again and again. Also, it allows us to add more features (i.e. members) to a class without modifying it. In this tutorial, we will learn how to use inheritance in Python.
Inheritance Syntax is given below:
class ParentClass: Body of parent class class ChildClass(ParentClass): Body of derived class
A class can also inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax:
class ChildClass(ParentClass 1, ParentClass 2, ... , ParentClass n):
Body of derived class
To demonstrate the use of inheritance, let us take an example where Area is the parent class and Volume is the child class. Here Area class is having two attributes named length & breadth and one method named computeArea(). By inheritance property, Volume class will acquire all these things from its parent class; additionally it will have a new attribute named height and a new method named computeVolume().
Now, we will create objects of both these classes to access the members. See the code below:
# Parent class
class Area:
# Parent Constructor
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth
def computeArea(self):
return self.length * self.breadth
# Child class
class Volume(Area):
# Child Constructor
def __init__(self, len, bre, height):
Area.__init__(self, len, bre) # Calling Parent class constructor
self.height = height # Adding new attribute
# Adding new method
def computeVolume(self):
return self.length * self.breadth * self.height
# Object of Parent class
a = Area(20, 10)
print("AREA1:", a.computeArea())
# Object of Child class
b = Volume(20, 15, 12)
print("AREA2:", b.computeArea()) # Can call the method of Parent class
print("VOLUME:", b.computeVolume())
Output:
AREA1: 200
AREA2: 300
VOLUME: 3600