Abstract Base Classes (ABCs) in Python are a form of interface checking more strict than the informal interfaces provided by duck-typing. They are modules that allow you to define abstract base classes, which are classes that can't be instantiated. Instead, other classes can inherit from these ABCs and implement their methods, ensuring they adhere to a particular interface.
The abc module in the Python standard library provides the infrastructure for defining ABCs.
Key components of the abc module include:
@abstractmethod: A decorator indicating abstract methods that must be implemented by any child classes.
ABC: A metaclass for ABCs. In Python 3.4+, you can also use it as a base class.
Here's a simple example demonstrating the use of ABCs:
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius * self.radius def perimeter(self): return 2 * 3.14 * self.radius # This will raise an error because `Shape` is abstract and can't be instantiated # s = Shape() # This will work c = Circle(5) print(c.area()) # Outputs: 78.5 print(c.perimeter()) # Outputs: 31.400000000000002
In this example, the Shape class is an abstract base class with two abstract methods, area and perimeter. The Circle class inherits from Shape and provides concrete implementations of the area and perimeter methods.
You'll get a TypeError if you try to create an instance of Shape directly or if you create a subclass of Shape that doesn't implement all its abstract methods.
Using ABCs helps provide a clear contract that derived classes must adhere to, ensuring a consistent interface and behavior for all subclasses.
typescript chown hashicorp-vault event-loop eloquent-relationship sprite-kit cross-join xunit.net symfony extend