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.
1. Basic Abstract Base Class
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!2. Abstract Class with Multiple Methods
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: 183. Preventing Instantiation of Abstract Classes
4. Partially Implemented Abstract Base Class
5. Abstract Properties
6. Abstract Base Class with Class Methods
7. Combining Abstract Base Class with Interfaces
8. Multiple Abstract Base Classes
9. Abstract Base Class with __init__
10. Using Abstract Base Class for Type Checking
Last updated