Python Programming – Python Single Inheritance
A program to represent the concept of single inheritance is displayed in Code 11.1. In this program, we create a base class shape that contains two data members’ length and breadth as shown in the constructor method __int__( ) of the class shape. The base class shape contains one class function display, which displays the values of length and breadth. Then, we create a class rectangle which is inheriting the features of the base class shape. By deriving, the member’s length, breadth, and display() of base class shape will become the members of a derived class rectangle as well apart from its own members’ area and compute_area(). Now, we create the object r1 of the derived class rectangle and calls the functions display() and compute_area() with the object of the rectangle. It is to be noted here that, we have not created the object of base class shape and just by creating the object of the derived class rectangle, we can access the data members and functions of the base class.
While the creation of object r1 of the derived class rectangle the constructor method __init__() of the derived class rectangle is invoked which further invokes the constructor method of base class shape. The init () method of base class shape inputs the values of length and breadth. Subsequently, the base class function display() is called by r1 .display(), which displays the values of length and breadth of the rectangle. In the end, the derived class function r1.compute_area() is called, which computes the area of a rectangle and displays the appropriate result. The output of the code is also given for verification.
Code: 11.1. Illustration of single inheritance.
|#illustration of single inheritance
class shape: #base class
def display(self): #display method of base class
class rectangle(shape): #derived class