Python abc Module
Example
Define an abstract base class and implement it:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, s):
self.s = s
def area(self):
return self.s * self.s
sq = Square(3)
print(isinstance(sq, Shape))
print(sq.area())
Try it Yourself »
Definition and Usage
The abc
module provides tools for creating Abstract Base Classes (ABCs) and decorators for abstract methods.
Use ABCs to define a common interface that subclasses must implement. This helps enforce contracts and improves clarity in larger codebases.
Members
Member | Description |
---|---|
ABC | Base class for defining abstract classes. |
ABCMeta | Metaclass used for defining ABCs; provides registration and abstract method checking. |
abstractclassmethod() | Deprecated. Use the classmethod decorator together with abstractmethod instead. |
abstractmethod() | Decorator to mark methods as abstract (must be overridden in subclasses). |
abstractproperty() | Deprecated. Use the property decorator together with abstractmethod instead. |
abstractstaticmethod() | Deprecated. Use the staticmethod decorator together with abstractmethod instead. |
get_cache_token() | Return the current ABC cache token (changes when ABCs are modified). |
update_abstractmethods() | Recompute the set of abstract methods for a class. |