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
‘A shape class’
def init (self):                                               #Constructor method of base class
self.length = float(input(‘Enter Length:’))
self.breadth = float(input(‘Enter Breadth:’))

def display(self):                                          #display method of base class
print (“\nLength: “, self.length)
print (“\nBreadth: ”, self.breadth)

class rectangle(shape):                                   #derived class
‘A rectangle class’
def __init__(self):                                         #Constructor method of derived class
shape.__init__(self)
self, area-0
def,dompute_area(self):                                    #compute_area function of derived class
self.area = self.length*self.breadth
print(“\nArea of rectangle-‘, self.area)
rl=rectangle()                                                 # object of derived class
rl.display()
r 1 .compute_area()

Output

Enter Length:6.5
Enter Breadth:7.8
Length: 6.5
Breadth: 7.8
Area of rectangle= 50.699999999999996

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *