Abstract Base Class (ABC) and abstractmethod

PHOTO EMBED

Thu Feb 22 2024 14:50:14 GMT+0000 (Coordinated Universal Time)

Saved by @aguest #python #classes

from abc import ABC, abstractmethod


class Shape(ABC):
# Shape is an abstract base class

    @abstractmethod
    def area(self):
        pass


class Circle(Shape):
# Circle is a class that inherits from the abstract Shape class

    def __init__(self, radius):
    	self.radius = radius
	
    def area(self):
   	# As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return 3.14 * self.radius ** 2


class Square(Shape):
# Square is a class that inherits from the abstract Shape class

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

    def area(self):
    # As a child of an Abstract class, this child class MUST define
    #	it's own implementation of this abstractmethod
    	return self.side ** 2
content_copyCOPY

Abstract classes are classes that contain one or more abstract methods and acts as a blueprint for child classes that inherit from the parent Abstract class. An Abstract class defines a common structure or interface for related classes, ensuring a certain level of consistency in their design.