Python Exercise 7

Mannan Ul Haq
0

Objective:

  • Concept of Polymorphism

Activity:

Task 1:

Create a class named Shape. Also, create classes Circle, Square, Triangle, and Rectangle as subclasses of the Shape class. Each subclass should override a calculate_area method of the Shape class. The initializers of these classes should take their respective dimensions as arguments.

Task 2:

In Python, all methods are virtually inherited by default. This means that if a method is overridden in a derived class, the overridden version of the method is invoked.


Solution:

class Shape:
    def __init__(self, color):
        self.color = color

    def calculate_area(self):
        return 0

    def __del__(self):
        print("~Shape() called.")


class Circle(Shape):
    def __init__(self, radius, color):
        super().__init__(color)
        self.radius = radius
        print("Circle constructor invoked.")

    def calculate_area(self):
        return 3.14 * self.radius * self.radius

    def __del__(self):
        print("~Circle() called.")


class Square(Shape):
    def __init__(self, side, color):
        super().__init__(color)
        self.side = side
        print("Square constructor invoked.")

    def calculate_area(self):
        return self.side * self.side

    def __del__(self):
        print("~Square() called.")


class Rectangle(Shape):
    def __init__(self, length, width, color):
        super().__init__(color)
        self.length = length
        self.width = width
        print("Rectangle constructor invoked.")

    def calculate_area(self):
        return self.length * self.width


class Triangle(Shape):
    def __init__(self, base, height, color):
        super().__init__(color)
        self.base = base
        self.height = height
        print("Triangle constructor invoked.")

    def calculate_area(self):
        return 0.5 * self.base * self.height

    def __del__(self):
        print("~Triangle() called.")


def main():
    t1 = Triangle(1.0, 9.0, "Red")
    c1 = Circle(2, "Blue")
    r1 = Rectangle(6, 2, "Orange")

    print(t1.calculate_area(), t1.color)
    print(c1.calculate_area())
    print(r1.calculate_area())

    sptr1 = t1
    sref = r1

    print(sptr1.calculate_area(), sptr1.color)
    print(sref.color, sref.calculate_area())

    s1 = Shape("Purple")

    def sum_area(shape1, shape2):
        return shape1.calculate_area() + shape2.calculate_area()

    print(sum_area(t1, c1))
    print(sum_area(s1, r1))
    print(sum_area(s1, t1))

main()


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !