Week 3 Assignment

The Assignment

This week we were asked to make a simple python program to familiarize and demonstrate knowledge on python programming, specifically python object oriented programming(POOP).

The program required us to create a base class called Shape and then create multiple subclasses representing different shapes. Each subclass implemented its own version of the area() method to calculate the area of that specific shape.

The shapes implemented in the program include:

I managed to complete the assignment, ran it without errors, below is the code.


import math

class Shape:
    def area(self):
        """
        This method should be implemented by subclasses
        """
        pass


class Circle(Shape):

    def __init__(self, diameter):
        self.diameter = diameter

    def area(self):
        r = self.diameter / 2
        Area = math.pi * r**2
        return Area


class Square(Shape):

    def __init__(self, length):
        self.length = length

    def area(self):
        Area = self.length**2
        return Area


class Rectangle(Shape):

    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        Area = self.width * self.length
        return Area


class RightTriangle(Shape):

    def __init__(self, base, height):
        self.base = base
        self.height = height

    def area(self):
        Area = (self.base * self.height) / 2
        return Area


# Test the program

circle = Circle(10)
square = Square(5)
rectangle = Rectangle(4, 6)
triangle = RightTriangle(3, 8)

print("Circle area:", circle.area())
print("Square area:", square.area())
print("Rectangle area:", rectangle.area())
print("Triangle area:", triangle.area())
⬅ Back to Home