In: Computer Science
Create an abstract class polygon that has a method getnoofsides() and getarea() and it has three subclasses triangle, rectangle and square each with its own two methods getnoofsides and getarea and their respective implementations accordingly.
python
from abc import ABC, abstractmethod
"""Python does not support abstract class but we have abc which stands for Abstract Base Classes for abstract class"""
class Polygon(ABC): # parent class
@abstractmethod
def getnoofsides(self):
pass
def getarea(self, b, h):
pass
def getareasquare(self, length): # square has all sides equal so only one parameter needed
pass
class Triangle(Polygon):
def getnoofsides(self):
super().getnoofsides() # super method to override the parent class method
print("It's a triangle with 3 sides")
def getarea(self, b, h):
super().getarea(b, h)
area = (1 / 2) * b * h
print("Area of triangle is:", area)
class Rectangle(Polygon):
def getnoofsides(self):
super().getnoofsides()
print("It's a Rectangle with 4 sides")
def getarea(self, b, h):
super().getarea(b, h)
area = h * b
print("Area of triangle is:", area)
class Square(Polygon):
def getnoofsides(self):
super().getnoofsides()
print("It's a square with 4 sides")
def getareasquare(self, length):
super().getareasquare(length)
areaofsquare = length * length
print("Area of square is:", areaofsquare)
T = Triangle()
T.getnoofsides()
T.getarea(float(input("Enter the breadth")), float(input("Enter the height"))) # float is used to change string input
# to float value (type casting)
R = Rectangle()
R.getnoofsides()
R.getarea(float(input("Enter the breadth")), float(input("Enter the length")))
S = Square()
S.getnoofsides()
S.getareasquare(float(input("Enter the length")))