abc
--- 抽象基类¶
源代码: Lib/abc.py
该模块提供了在 Python 中定义 抽象基类 (ABC) 的组件,在 PEP 3119 中已有概述。查看 PEP 文档了解为什么需要在 Python 中增加这个模块。(也可查看 PEP 3141 以及 numbers
模块了解基于 ABC 的数字类型继承关系。)
The collections
module has some concrete classes that derive from
ABCs; these can, of course, be further derived. In addition, the
collections.abc
submodule has some ABCs that can be used to test whether
a class or instance provides a particular interface, for example, if it is
hashable or if it is a mapping.
该模块提供了一个元类 ABCMeta
,可以用来定义抽象类,另外还提供一个工具类 ABC
,可以用它以继承的方式定义抽象基类。
- class abc.ABC¶
A helper class that has
ABCMeta
as its metaclass. With this class, an abstract base class can be created by simply deriving fromABC
avoiding sometimes confusing metaclass usage, for example:from abc import ABC class MyABC(ABC): pass
Note that the type of
ABC
is stillABCMeta
, therefore inheriting fromABC
requires the usual precautions regarding metaclass usage, as multiple inheritance may lead to metaclass conflicts. One may also define an abstract base class by passing the metaclass keyword and usingABCMeta
directly, for example:from abc import ABCMeta class MyABC(metaclass=ABCMeta): pass
3.4 新版功能.
- class abc.ABCMeta¶
用于定义抽象基类(ABC)的元类。
使用该元类以创建抽象基类。抽象基类可以像 mix-in 类一样直接被子类继承。你也可以将不相关的具体类(包括内建类)和抽象基类注册为“抽象子类” —— 这些类以及它们的子类会被内建函数
issubclass()
识别为对应的抽象基类的子类,但是该抽象基类不会出现在其 MRO(Method Resolution Order,方法解析顺序)中,抽象基类中实现的方法也不可调用(即使通过super()
调用也不行)。1Classes created with a metaclass of
ABCMeta
have the following method:- register(subclass)¶
将“子类”注册为该抽象基类的“抽象子类”,例如:
from abc import ABC class MyABC(ABC): pass MyABC.register(tuple) assert issubclass(tuple, MyABC) assert isinstance((), MyABC)
在 3.3 版更改: 返回注册的子类,使其能够作为类装饰器。
在 3.4 版更改: To detect calls to
register()
, you can use theget_cache_token()
function.
你也可以在虚基类中重载这个方法。
- __subclasshook__(subclass)¶
(必须定义为类方法。)
Check whether subclass is considered a subclass of this ABC. This means that you can customize the behavior of
issubclass()
further without the need to callregister()
on every class you want to consider a subclass of the ABC. (This class method is called from the__subclasscheck__()
method of the ABC.)该方法必须返回
True
,False
或是NotImplemented
。如果返回True
,subclass 就会被认为是这个抽象基类的子类。如果返回False
,无论正常情况是否应该认为是其子类,统一视为不是。如果返回NotImplemented
,子类检查会按照正常机制继续执行。
为了对这些概念做一演示,请看以下定义 ABC 的示例:
class Foo: def __getitem__(self, index): ... def __len__(self): ... def get_iterator(self): return iter(self) class MyIterable(ABC): @abstractmethod def __iter__(self): while False: yield None def get_iterator(self): return self.__iter__() @classmethod def __subclasshook__(cls, C): if cls is MyIterable: if any("__iter__" in B.__dict__ for B in C.__mro__): return True return NotImplemented MyIterable.register(Foo)
The ABC
MyIterable
defines the standard iterable method,__iter__()
, as an abstract method. The implementation given here can still be called from subclasses. Theget_iterator()
method is also part of theMyIterable
abstract base class, but it does not have to be overridden in non-abstract derived classes.这里定义的
__subclasshook__()
类方法指明了任何在其__dict__
(或在其通过__mro__
列表访问的基类) 中具有__iter__()
方法的类也都会被视为MyIterable
。Finally, the last line makes
Foo
a virtual subclass ofMyIterable
, even though it does not define an__iter__()
method (it uses the old-style iterable protocol, defined in terms of__len__()
and__getitem__()
). Note that this will not makeget_iterator
available as a method ofFoo
, so it is provided separately.
The abc
module also provides the following decorator:
- @abc.abstractmethod¶
用于声明抽象方法的装饰器。
Using this decorator requires that the class's metaclass is
ABCMeta
or is derived from it. A class that has a metaclass derived fromABCMeta
cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms.abstractmethod()
may be used to declare abstract methods for properties and descriptors.Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are only supported using the
update_abstractmethods()
function. Theabstractmethod()
only affects subclasses derived using regular inheritance; "virtual subclasses" registered with the ABC'sregister()
method are not affected.When
abstractmethod()
is applied in combination with other method descriptors, it should be applied as the innermost decorator, as shown in the following usage examples:class C(ABC): @abstractmethod def my_abstract_method(self, arg1): ... @classmethod @abstractmethod def my_abstract_classmethod(cls, arg2): ... @staticmethod @abstractmethod def my_abstract_staticmethod(arg3): ... @property @abstractmethod def my_abstract_property(self): ... @my_abstract_property.setter @abstractmethod def my_abstract_property(self, val): ... @abstractmethod def _get_x(self): ... @abstractmethod def _set_x(self, val): ... x = property(_get_x, _set_x)
In order to correctly interoperate with the abstract base class machinery, the descriptor must identify itself as abstract using
__isabstractmethod__
. In general, this attribute should beTrue
if any of the methods used to compose the descriptor are abstract. For example, Python's built-inproperty
does the equivalent of:class Descriptor: ... @property def __isabstractmethod__(self): return any(getattr(f, '__isabstractmethod__', False) for f in (self._fget, self._fset, self._fdel))
备注
不同于 Java 抽象方法,这些抽象方法可能具有一个实现。 这个实现可在重载它的类上通过
super()
机制来调用。 这在使用协作多重继承的框架中可以被用作 super 调用的一个终点。
The abc
module also supports the following legacy decorators:
- @abc.abstractclassmethod¶
3.2 新版功能.
3.3 版后已移除: 现在可以让
classmethod
配合abstractmethod()
使用,使得此装饰器变得冗余。内置
classmethod()
的子类,指明一个抽象类方法。 在其他方面它都类似于abstractmethod()
。这个特例已被弃用,因为现在当
classmethod()
装饰器应用于抽象方法时它会被正确地标识为抽象的:class C(ABC): @classmethod @abstractmethod def my_abstract_classmethod(cls, arg): ...
- @abc.abstractstaticmethod¶
3.2 新版功能.
3.3 版后已移除: 现在可以让
staticmethod
配合abstractmethod()
使用,使得此装饰器变得冗余。内置
staticmethod()
的子类,指明一个抽象静态方法。 在其他方面它都类似于abstractmethod()
。这个特例已被弃用,因为现在当
staticmethod()
装饰器应用于抽象方法时它会被正确地标识为抽象的:class C(ABC): @staticmethod @abstractmethod def my_abstract_staticmethod(arg): ...
- @abc.abstractproperty¶
3.3 版后已移除: 现在可以让
property
,property.getter()
,property.setter()
和property.deleter()
配合abstractmethod()
使用,使得此装饰器变得冗余。内置
property()
的子类,指明一个抽象特性属性。这个特例已被弃用,因为现在当
property()
装饰器应用于抽象方法时它会被正确地标识为抽象的:class C(ABC): @property @abstractmethod def my_abstract_property(self): ...
上面的例子定义了一个只读特征属性;你也可以通过适当地将一个或多个下层方法标记为抽象的来定义可读写的抽象特征属性:
class C(ABC): @property def x(self): ... @x.setter @abstractmethod def x(self, val): ...
如果只有某些组件是抽象的,则只需更新那些组件即可在子类中创建具体的特征属性:
class D(C): @C.x.setter def x(self, val): ...
The abc
module also provides the following functions:
- abc.get_cache_token()¶
返回当前抽象基类的缓存令牌
此令牌是一个不透明对象(支持相等性测试),用于为虚子类标识抽象基类缓存的当前版本。 此令牌会在任何 ABC 上每次调用
ABCMeta.register()
时发生更改。3.4 新版功能.
- abc.update_abstractmethods(cls)¶
重新计算一个抽象类的抽象状态的函数。 如果一个类的抽象方法在类被创建后被实现或被修改则应当调用此函数。 通常,此函数应当在一个类装饰器内部被调用。
返回 cls,使其能够用作类装饰器。
如果 cls 不是
ABCMeta
的子类,则不做任何操作。备注
此函数会假定 cls 的上级类已经被更新。 它不会更新任何子类。
3.10 新版功能.
备注
- 1
C++ 程序员需要注意:Python 中虚基类的概念和 C++ 中的并不相同。