PYTHON: Develop an inheritance hierarchy based upon a Polygon class that has abs
ID: 3879090 • Letter: P
Question
PYTHON: Develop an inheritance hierarchy based upon a Polygon class that has abstract methods area( ) and perimeter( ). Implement classes Triangle, Quadrilateral, Pentagon, Hexagon, and Octagon that extend this base class, with the obvious meanings for the area( ) and perimeter( ) methods. Also implement classes, IsoscelesTriangle, EquilateralTriangle, Rectangle, and Square, that have the appropriate inheritance relationships. Finally, write a simple program that allows users to create polygons of the various types and input their geometric dimensions, and the program then outputs their area and perimeter.. Do it with Python
Explanation / Answer
from abc import ABCMeta, abstractmethod
class Polygon(object):
__metaclass__ = ABCMeta
def __init__(self, n):
self.number_of_sides = n
def print_num_sides(self):
print('There are ' + str(self.number_of_sides) + 'sides.')
@abstractmethod
def get_area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Polygon):
def __init__(self, length, breadth):
super().__init__()
self.__length = length
self.__breadth = breadth
def get_area(self):
return self.__length * self.__breadth
def get_perimeter(self):
return 2 * (self.__length + self.__breadth)
class Triangle(Polygon):
def __init__(self, lengths_of_sides):
Polygon.__init__(self, 3)
self.lengths_of_sides = lengths_of_sides # list of three numbers
def get_area(self):
'''return the area of the triangle using the semi-perimeter method'''
a, b, c = self.lengths_of_sides
# calculate the semi-perimeter
s = (a + b + c) / 2
return (s*(s-a)*(s-b)*(s-c)) ** 0.5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.