Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Example of inheritance and constructor in subclass

class Polygon:
    
    #Constructor
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]
        
    #Take user input for side lenghts    
    def inputSides(self):
        self.sides = [int(input("Enter Side: ")) for i in range(self.n)]
        
    #Print the sides of the polygon
    def displaySides(self):
        for i in range(self.n):
            print("Side",i+1,"is",self.sides[i])
            
class Triangle(Polygon):
    
    def __init__(self):
        #Calling constructor of superclass
        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)
Source by www.codingninjas.com #
 
PREVIOUS NEXT
Tagged: #Example #inheritance #constructor #subclass
ADD COMMENT
Topic
Name
9+8 =