# 28.8. `abc` — 抽象基类

2.6 新版功能.

源代码： 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` module 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.

This module provides the following class:

class `abc.``ABCMeta`

  用于定义抽象基类（ABC）的元类。

  使用该元类以创建抽象基类。抽象基类可以像 mix-in 类一样直接被子类继承。你也可以将不相关的具体类（包括内建类）和抽象基类注册为“抽象子类” —— 这些类以及它们的子类会被内建函数 `issubclass()` 识别为对应的抽象基类的子类，但是该抽象基类不会出现在其 MRO（Method Resolution Order，方法解析顺序）中，抽象基类中实现的方法也不可调用（即使通过 `super()` 调用也不行）。1

  使用 `ABCMeta` 作为元类创建的类含有如下方法：

  `register`(subclass)

    将“子类”注册为该抽象基类的“抽象子类”，例如：

        from abc import ABCMeta

        class MyABC:
            __metaclass__ = ABCMeta

        MyABC.register(tuple)

        assert issubclass(tuple, MyABC)
        assert isinstance((), MyABC)

  你也可以在虚基类中重载这个方法。

  `__subclasshook__`(subclass)

    （必须定义为类方法。）

    检查 subclass 是否是该抽象基类的子类。也就是说对于那些你希望定义为该抽象基类的子类的类，你不用对每个类都调用 `register()` 方法了，而是可以直接自定义 `issubclass` 的行为。（这个类方法是在抽象基类的 `__subclasscheck__()` 方法中调用的。）

    该方法必须返回 `True`, `False` 或是 `NotImplemented`。如果返回 `True`，subclass 就会被认为是这个抽象基类的子类。如果返回 `False`，无论正常情况是否应该认为是其子类，统一视为不是。如果返回 `NotImplemented`，子类检查会按照正常机制继续执行。

  为了对这些概念做一演示，请看以下定义 ABC 的示例：

      class Foo(object):
          def __getitem__(self, index):
              ...
          def __len__(self):
              ...
          def get_iterator(self):
              return iter(self)

      class MyIterable:
          __metaclass__ = ABCMeta

          @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)

  ABC `MyIterable` 定义了标准的迭代方法 `__iter__()` 作为一个抽象方法。这里给出的实现仍可在子类中被调用。`get_iterator()` 方法也是 `MyIterable` 抽象基类的一部分，但它并非必须被非抽象派生类所重载。

  The `__subclasshook__()` class method defined here says that any class that has an `__iter__()` method in its `__dict__` (or in that of one of its base classes, accessed via the `__mro__` list) is considered a `MyIterable` too.

  Finally, the last line makes `Foo` a virtual subclass of `MyIterable`, 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 make `get_iterator` available as a method of `Foo`, so it is provided separately.

It also provides the following decorators:

`abc.``abstractmethod`(function)

  用于声明抽象方法的装饰器。

  Using this decorator requires that the class’s metaclass is `ABCMeta` or is derived from it. A class that has a metaclass derived from `ABCMeta` 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.

  Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are not supported. The `abstractmethod()` only affects subclasses derived using regular inheritance; “virtual subclasses” registered with the ABC’s `register()` method are not affected.

  Usage:

      class C:
          __metaclass__ = ABCMeta
          @abstractmethod
          def my_abstract_method(self, ...):
              ...

  注解

  Unlike Java abstract methods, these abstract methods may have an implementation. This implementation can be called via the `super()` mechanism from the class that overrides it. This could be useful as an end-point for a super-call in a framework that uses cooperative multiple-inheritance.

`abc.``abstractproperty`([fget[, fset[, fdel[, doc]]]])

  A subclass of the built-in `property()`, indicating an abstract property.

  Using this function requires that the class’s metaclass is `ABCMeta` or is derived from it. A class that has a metaclass derived from `ABCMeta` cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract properties can be called using any of the normal ‘super’ call mechanisms.

  Usage:

      class C:
          __metaclass__ = ABCMeta
          @abstractproperty
          def my_abstract_property(self):
              ...

  This defines a read-only property; you can also define a read-write abstract property using the ‘long’ form of property declaration:

      class C:
          __metaclass__ = ABCMeta
          def getx(self): ...
          def setx(self, value): ...
          x = abstractproperty(getx, setx)

备注

1

  C++ 程序员需要注意：Python 中虚基类的概念和 C++ 中的并不相同。