abc --- 抽象基底クラス

ソースコード: Lib/abc.py


このモジュールは Python に PEP 3119 で概要が示された 抽象基底クラス (ABC) を定義する基盤を提供します。なぜこれが Python に付け加えられたかについてはその PEP を参照してください。 (ABC に基づいた数の型階層を扱った PEP 3141numbers モジュールも参照してください。)

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 from ABC avoiding sometimes confusing metaclass usage, for example:

from abc import ABC

class MyABC(ABC):
    pass

Note that the type of ABC is still ABCMeta, therefore inheriting from ABC 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 using ABCMeta directly, for example:

from abc import ABCMeta

class MyABC(metaclass=ABCMeta):
    pass

バージョン 3.4 で追加.

class abc.ABCMeta

抽象基底クラス(ABC)を定義するためのメタクラス。

ABC を作るときにこのメタクラスを使います。ABC は直接的にサブクラス化することができ、ミックスイン(mix-in)クラスのように振る舞います。また、無関係な具象クラス(組み込み型でも構いません)と無関係な ABC を "仮想的サブクラス" として登録できます -- これらとその子孫は組み込み関数 issubclass() によって登録した ABC のサブクラスと判定されますが、登録した ABC は MRO (Method Resolution Order, メソッド解決順)には現れませんし、この ABC のメソッド実装が(super() を通してだけでなく)呼び出し可能になるわけでもありません。 [1]

Classes created with a metaclass of ABCMeta have the following method:

register(subclass)

subclass を "仮想的サブクラス" としてこの ABC に登録します。たとえば:

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 the get_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 call register() on every class you want to consider a subclass of the ABC. (This class method is called from the __subclasscheck__() method of the ABC.)

This method should return True, False or NotImplemented. If it returns True, the subclass is considered a subclass of this ABC. If it returns False, the subclass is not considered a subclass of this ABC, even if it would normally be one. If it returns NotImplemented, the subclass check is continued with the usual mechanism.

この概念のデモとして、次の 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. The get_iterator() method is also part of the MyIterable abstract base class, but it does not have to be overridden in non-abstract derived classes.

ここで定義されるクラスメソッド __subclasshook__() の意味は、 __iter__() メソッドがクラスの(または __mro__ でアクセスされる基底クラスの一つの) __dict__ にある場合にもそのクラスが MyIterable だと見なされるということです。

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.

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 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. 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. The abstractmethod() only affects subclasses derived using regular inheritance; "virtual subclasses" registered with the ABC's register() 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 be True if any of the methods used to compose the descriptor are abstract. For example, Python's built-in property 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 で非推奨: classmethodabstractmethod() と一緒に使えるようになったため、このデコレータは冗長になりました。

組み込みの classmethod() のサブクラスで、抽象クラスメソッドであることを示します。それ以外は abstractmethod() と同じです。

この特殊ケースは classmethod() デコレータが抽象メソッドに適用された場合に抽象的だと正しく認識されるようになったため撤廃されます:

class C(ABC):
    @classmethod
    @abstractmethod
    def my_abstract_classmethod(cls, arg):
        ...
@abc.abstractstaticmethod

バージョン 3.2 で追加.

バージョン 3.3 で非推奨: staticmethodabstractmethod() と一緒に使えるようになったため、このデコレータは冗長になりました。

組み込みの staticmethod() のサブクラスで、抽象静的メソッドであることを示します。それ以外は abstractmethod() と同じです。

この特殊ケースは staticmethod() デコレータが抽象メソッドに適用された場合に抽象的だと正しく認識されるようになったため撤廃されます:

class C(ABC):
    @staticmethod
    @abstractmethod
    def my_abstract_staticmethod(arg):
        ...
@abc.abstractproperty

バージョン 3.3 で非推奨: propertyproperty.getter()property.setter() および property.deleter()abstractmethod() と一緒に使えるようになったため、このデコレータは冗長になりました。

組み込みの property() のサブクラスで、抽象プロパティであることを示します。

この特殊ケースは property() デコレータが抽象メソッドに適用された場合に抽象的だと正しく認識されるようになったため撤廃されます:

class C(ABC):
    @property
    @abstractmethod
    def my_abstract_property(self):
        ...

この例は読み出し専用のプロパティを定義しています。プロパティを構成するメソッドの1つ以上を abstract にすることで、読み書きできる抽象プロパティを定義することができます:

class C(ABC):
    @property
    def x(self):
        ...

    @x.setter
    @abstractmethod
    def x(self, val):
        ...

構成するメソッド全てが abstract でない場合、abstract と定義されたメソッドのみが、具象サブクラスによってオーバーライドする必要があります:

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)

A function to recalculate an abstract class's abstraction status. This function should be called if a class's abstract methods have been implemented or changed after it was created. Usually, this function should be called from within a class decorator.

Returns cls, to allow usage as a class decorator.

If cls is not an instance of ABCMeta, does nothing.

注釈

This function assumes that cls's superclasses are already updated. It does not update any subclasses.

バージョン 3.10 で追加.

脚注