Python Abstract Class with Concrete Subclasses
Define an abstract base class with abstract methods and implement them in concrete subclasses like Rectangle and Circle.
Python code
40 linesfrom 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)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
def perimeter(self):
return 2 * 3.14159 * self.radius
if __name__ == "__main__":
rect = Rectangle(5, 3)
print(f"Rectangle area: {rect.area()}")
print(f"Rectangle perimeter: {rect.perimeter()}")
circle = Circle(4)
print(f"Circle area: {circle.area():.2f}")
print(f"Circle perimeter: {circle.perimeter():.2f}")
Output
Rectangle area: 15
Rectangle perimeter: 16
Circle area: 50.27
Circle perimeter: 25.13
How it works
The ABC class from the abc module marks a class as abstract. Methods decorated with @abstractmethod must be overridden in any concrete subclass. Attempting to instantiate Shape directly raises a TypeError, enforcing the contract. Each subclass provides its own implementation of area and perimeter, so callers can treat all shapes uniformly.
Common mistakes
- Forgetting to inherit from ABC or missing @abstractmethod decorator
- Trying to instantiate the abstract class directly
- Forgetting to implement all abstract methods in the subclass
Variations
- Use `@property` on abstract methods to require read-only attributes.
- Use dataclasses for subclasses to reduce boilerplate.
Real-world use cases
- Define a common interface for payment processors (e.g., charge, refund) enforced across providers.
- Build a plugin system where each plugin must implement required hooks.
- Model geometric shapes for a rendering engine that needs a uniform area calculation interface.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.