18  Class: Shape

18.0.1 Parent: Shape

from abc import ABC, abstractmethod

class Shape(ABC):

    count = 0
    
    def __init__(self, color):
        self.color = color
        self.count += 1
    
    # For Dev
    def __repr__(self) -> str:
        cls = self.__class__.__name__
        return f"{cls}(color={self.color})"
    # For User
    def __str__(self) -> str:
        cls = self.__class__.__name__
        return f"{cls} with {self.color} color"
    
    @abstractmethod
    def area(self):
        pass

    

18.0.2 Child Class

class Circle(Shape):
    def __init__(self, color, radius):
        super().__init__(color)
        self.radius = radius
        
    def area(self):
        import math
        A = math.pi * self.radius ** 2
        return f"The circle area = pi x {self.radius}^2 = {A}"
class Square(Shape):
    def __init__(self, color, side):
        super().__init__(color)
        self.side = side
    def area(self):
        return f"The square area = {self.side ** 2}"
class Triangle(Shape):
    def __init__(self, color, width, height):
        super().__init__(color)
        self.width = width
        self.height = height
    def area(self):
        return f"The triangle area = {self.width * self.height * 0.5}"

18.0.3 Instantiate

circle1 = Circle(color = "Red", radius=3)
print(circle1)
circle1
Circle with Red color
Circle(color=Red)
circle1.area()
'The circle area = pi x 3^2 = 28.274333882308138'
square1 = Square(color = "Pink", side=5)
print(square1.count)
square1
1
Square(color=Pink)
square1.area()
'The square area = 25'
triangle1 = Triangle(color="Yellow", width=4, height = 10)
triangle1
Triangle(color=Yellow)
triangle1.area()
'The triangle area = 20.0'