Polygon, Rectangle and Triangle Class in Python
Posted by Samath
Last Updated: January 20, 2024

Consider three classes polygon, rectangle and triangle, where polygon is the superclass and rectangle and triangle are its subclasses.

Complete the implementation of the rectangle class which takes three arguments no-sides (number of sides), breadth and length to create a rectangle object. The rectangle class is a subclass of polygon class. Implement messages area and perimeter for the rectangle class using the formulae given below.

Test your implementation using the following expressions;
>>> r1=rectangle(2,4)
>>> r1.area()
8
>>> r1.howmanysides()
4
>>> r1.perimeter()
12
>>>

Complete the implementation of the triangle class which takes four arguments no-sides (number of sides) and the three sides of a triangle a, b and c to create a triangle object. The triangle class is a subclass of polygon class. Implement messages area and perimeter for the triangle class using the formulae given below.

Test your implementation using the following expressions;
>>> t1=triangle(5,5,5)
>>> t1.area()
10.825317547305483
>>> t1.howmanysides()
3
>>> t1.perimeter()
15

Code:

  1. import math
  2. class Polygon:
  3. def __init__(self,nbrsides):
  4. self.nbr_sides = nbrsides
  5.  
  6. def whoamI(self):
  7. if self.nbr_sides == 3:
  8. return "Triangle"
  9. elif self.nbr_sides == 4:
  10. return "Rectangle"
  11. else: return "Polygon"
  12.  
  13. def howmanysides(self):
  14. return self.nbr_sides
  15.  
  16. def area(self):
  17. return "No Area"
  18.  
  19. def perimeter(self):
  20. return "No Perimeter"
  21.  
  22.  
  23.  
  24. class triangle(Polygon):
  25. def __init__(self,a,b,c):
  26. Polygon.__init__(self, 3)
  27. self.a = a
  28. self.b = b
  29. self.c = c
  30.  
  31. def area(self):
  32. s = (self.a + self.b + self.c)/2
  33. area = math.sqrt(s*((s-self.a)*(s-self.b)*(s-self.c)))
  34. return area
  35.  
  36. def perimeter(self):
  37. return self.a + self.b + self.c
  38.  
  39.  
  40. class rectangle(Polygon):
  41. def __init__(self,breadth,length):
  42. Polygon.__init__(self, 4)
  43. self.breadth = breadth
  44. self.length = length
  45.  
  46. def area(self):
  47. return self.length * self.breadth
  48.  
  49. def perimeter(self):
  50. return 2 * (self.length + self.breadth)
  51.  
  52.  
  53.  
  54.  
  55. def main():
  56. tri1=triangle(2,2,2)
  57. rect=rectangle(2,3)
  58. tri2=triangle(3,3,3)
  59. figures = [tri1,rect,tri2]
  60. for fig in figures:
  61. print ("Type of Polygon =>", fig.whoamI())
  62. print ("Sides =", fig.howmanysides())
  63. print ("Area =", fig.area())
  64. print ("Perimeter =", fig.perimeter())