使用 ABC 和使用 ABCMeta 有什么区别吗?

在 Python 3.4 + 中,我们可以

class Foo(abc.ABC):
...

或者我们可以

class Foo(metaclass=abc.ABCMeta):
...

这两者之间有什么我需要注意的区别吗?

25698 次浏览

abc.ABC basically just an extra layer over metaclass=abc.ABCMeta. i.e abc.ABC implicitly defines the metaclass for us.

(Source: 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 has ABCMeta as its meta class. Using ABC as a base class has essentially the same effect as specifying metaclass=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__