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

Copy

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

Copy

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: 18

3. Preventing Instantiation of Abstract Classes

Copy


4. Partially Implemented Abstract Base Class

Copy


5. Abstract Properties

Copy


6. Abstract Base Class with Class Methods

Copy


7. Combining Abstract Base Class with Interfaces

Copy


8. Multiple Abstract Base Classes

Copy


9. Abstract Base Class with __init__

Copy


10. Using Abstract Base Class for Type Checking

Copy

Last updated