5. Abstract Base Classes (ABCs
These examples demonstrate how abc can be used to enforce method implementation in subclasses, ensure adherence to interfaces, and provide a clear structure for abstract behavior.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
return "Woof!"
dog = Dog()
print(dog.make_sound()) # Output: Woof!from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
rect = Rectangle(4, 5)
print(rect.area()) # Output: 20
print(rect.perimeter()) # Output: 18Last updated