Python 3.4以降では、
class Foo(abc.ABC):
...
あるいは
class Foo(metaclass=abc.ABCMeta):
...
これら 2 つの違いについて知っておくべき点はありますか?
ベストアンサー1
abc.ABC
基本的には、 の上に追加のレイヤーを追加するだけですmetaclass=abc.ABCMeta
。つまり、abc.ABC
暗黙的にメタクラスを定義します。
(ソース:https://hg.python.org/cpython/file/3.4/Lib/abc.py#l234)
class ABC(metaclass=ABCMeta):
"""Helper class that provides a standard way to create an ABC using
inheritance.
"""
pass
The only difference is that in the former case you need a simple inheritance and in the latter you need to specify the metaclass.
From What's new in Python 3.4(emphasis mine):
New class
ABC
hasABCMeta
as its meta class. UsingABC
as a base class has essentially the same effect as specifyingmetaclass=abc.ABCMeta
, but is simpler to type and easier to read.
Related issue: Create abstract base classes by inheritance rather than a direct invocation of __metaclass__