Definition
Inheritance enable us to define a class that takes all the functionality from parent class and allows us to add more.
The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.
Syntax
class derivedclass(baseclass):
...
Example
import math
#Base Class - quadrilateral
class quadrilateral:
def __init__(self,s1,s2,s3,s4):
self.side1 = s1;
self.side2 = s2;
self.side3 = s3;
self.side4 = s4;
def get_perimeter(self):
return self.side1 + self.side2 + self.side3 + self.side4;
#Derived Class - rectangle
class rectangle(quadrilateral):
def __init__(self, l, w):
self.side1 = l;
self.side2 = w;
self.side3 = l;
self.side4 = w;
def get_diagonal(self): #get the length of a diagonal
return math.sqrt(self.side1**2 + self.side2**2);
#demo
quad = quadrilateral(3,4,5,5) #create an object from the quadrilateral class with side lengths 3, 4, 5, and 5.
print(quad.get_perimeter()) #output the perimeter of the object quad which is 17
rect = rectangle(3,4)
print(rect.get_perimeter()) #output the perimeter of the object rect which is 14. Notice that the get_perimeter is not declared in the rectangle class but rather is inherited from the quadrilateral class.
print(rect.get_diagonal()) #output the length of the diagonal of the object rect which is 5.0.