To define an abstract class in Python, you inherit from the
ABChelper class and use the@abstractmethoddecorator from the built-in abc module.An abstract class acts as a blueprint that cannot be instantiated directly. It forces any child class to implement its abstract methods.
Key Rules and Features
Preventing Direct Instantiation. Attempting to create an object directly from an abstract class with unimplemented abstract methods raises a
TypeErrorEnforcing Subclass Implementation. Any concrete subclass must override every method marked with
@abstractmethod. If a subclass misses even one, Python treats that subclass as abstract too and blocks instantiation.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
def describe(self):
return "This is a shape."
class Square(Shape):
def __init__(self, side):
self.side = side
# Must implement the abstract method
def area(self):
return self.side * self.side
# shape = Shape() # Raises TypeError: Can't instantiate abstract class
sq = Square(4)
print(sq.area()) # Output: 16
print(sq.describe()) # Output: This is a shape.