Python 简明教程
Python - Abstract Base Classes
在 Python 中, Abstract Base Class (ABC) 是一个不能直接实例化的类,旨在被子类化。ABC 通过提供所有子类都必须实现的通用接口,充当其他类别的蓝图。
An Abstract Base Class (ABC) in Python is a class that cannot be instantiated directly and is intended to be subclassed. ABCs serve as blueprints for other classes by providing a common interface that all subclasses must implement.
它们是 object-oriented programming in Python 中的基本组成部分,它使开发人员能够为一组相关类定义和实施一致的 API。
They are a fundamental part of object-oriented programming in Python which enables the developers to define and enforce a consistent API for a group of related classes.
Purpose of Abstract Base Classes
以下是 Abstract Base Classes of Python 的用途和功能的深入分析 −
Here’s an in-depth look at the purpose and functionality of the Abstract Base Classes of Python −
Defining a Standard Interface
Abstract Base Class (ABC) 允许我们为其他类定义一个蓝图。该蓝图确保从 Abstract Base Class (ABC) 派生的任何类都通过提供一致的接口来实现某些方法。
Abstract Base Class (ABC) allow us to define a blueprint for other classes. This blueprint ensures that any class deriving from the Abstract Base Class (ABC) implements certain methods by providing a consistent interface.
以下是定义 Python 中抽象基类的标准接口的示例代码 −
Following is the example code of defining the standard Interface of the Abstract Base Class in Python −
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
Enforcing Implementation
当类从 Abstract Base Class (ABC) 继承时,它必须实现所有 abstract methods 。如果不实现,Python 就会引发 TypeError。以下是 Python 中执行抽象基类实现的示例 −
When a class inherits from an Abstract Base Class (ABC) it must implement all abstract methods. If it doesn’t then Python will raise a TypeError. Here is the example of enforcing implementation of the Abstract Base Class in Python −
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)
# This will work
rect = Rectangle(5, 10)
# This will raise TypeError
class IncompleteShape(Shape):
pass
Providing a Template for Future Development
Abstract Base Class (ABC) 在多个开发人员可能处理代码库中不同部分的大型项目中很有用。它们为开发人员提供了一个明确的模板,以确保一致性和减少错误。
Abstract Base Class (ABC) is useful in large projects where multiple developers might work on different parts of the codebase. They provide a clear template for developers to follow which ensure consistency and reducing errors.
Facilitating Polymorphism
Abstract Base Class (ABC) 通过支持与来自不同类的对象进行操作的代码的开发,只要它们符合特定接口,就能使多态性成为可能。此能力简化了代码的扩展和维护。
Abstract Base Class (ABC) make polymorphism possible by enabling the development of code that can operate with objects from diverse classes as long as they conform to a specific interface. This capability streamlines the extension and upkeep of code.
以下是 Python 抽象基类中实现多态性的示例 −
Below is the example of Facilitating Polymorphism in Abstract Base Class of Python −
def print_shape_info(shape: Shape):
print(f"Area: {shape.area()}")
print(f"Perimeter: {shape.perimeter()}")
square = Rectangle(4, 4)
print_shape_info(square)
Note: 要执行上述示例代码,有必要定义标准接口和强制实现。
Note: To execute the above mentioned example codes, it is necessary to define the standard interface and Enforcing Implementation.
Components of Abstract Base Classes
Python 中的 Abstract Base Classes (ABCs) 包含几个关键组件,使它们能够为子类定义和强制实现接口。
Abstract Base Classes (ABCs) in Python consist of several key components that enable them to define and enforce interfaces for subclasses.
这些组件包括 ABC 类、抽象方法装饰器以及其他一些用于创建和管理抽象基类的组件。以下是抽象基类的主要组成部分 −
These components include the ABC class, the abstractmethod decorator and several others that help in creating and managing abstract base classes. Here are the key components of Abstract Base Classes −
-
ABC Class: This class from Python’s Abstract Base Classes (ABCs) module serves as the foundation for creating abstract base classes. Any class derived from ABC is considered an abstract base class.
-
'abstractmethod' Decorator: This decorator from the abc module is used to declare methods as abstract. These methods do not have implementations in the ABC and must be overridden in derived classes.
-
'ABCMeta' Metaclass: This is the metaclass used by ABC. It is responsible for keeping track of which methods are abstract and ensuring that instances of the abstract base class cannot be created if any abstract methods are not implemented.
-
Concrete Methods in ABCs: Abstract base classes can also define concrete methods that provide a default implementation. These methods can be used or overridden by subclasses.
-
Instantiation Restrictions: A key feature of ABCs is that they cannot be instantiated directly if they have any abstract methods. Attempting to instantiate an ABC with unimplemented abstract methods will raise a 'TypeError'.
-
Subclass Verification: Abstract Base Classes (ABCs) can verify if a given class is a subclass using the issubclass function and can check instances with the isinstance function.
Example of Abstract Base Classes in Python
以下示例显示了 ABC 如何强制方法实现、支持 polymorphism 以及为相关类提供清晰而一致的接口 −
Following example shows how ABCs enforce method implementation, support polymorphism and provide a clear and consistent interface for related classes −
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
def description(self):
return "I am a shape."
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):
import math
return math.pi * self.radius ** 2
def perimeter(self):
import math
return 2 * math.pi * self.radius
def print_shape_info(shape):
print(shape.description())
print(f"Area: {shape.area()}")
print(f"Perimeter: {shape.perimeter()}")
shapes = [Rectangle(5, 10), Circle(7)]
for shape in shapes:
print_shape_info(shape)
print("-" * 20)
class IncompleteShape(Shape):
pass
try:
incomplete_shape = IncompleteShape()
except TypeError as e:
print(e)
Output
执行上述代码,我们将得到以下输出 −
On executing the above code we will get the following output −
I am a shape.
Area: 50
Perimeter: 30
--------------------
I am a shape.
Area: 153.93804002589985
Perimeter: 43.982297150257104
--------------------
Can't instantiate abstract class IncompleteShape with abstract methods area, perimeter