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

2024-05-13 20:55:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3.4+中,我们可以

class Foo(abc.ABC):
    ...

或者我们可以

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

我应该知道这两者之间有什么不同吗?


Tags: fooclassmetaclassabcabcmeta
1条回答
网友
1楼 · 发布于 2024-05-13 20:55:41

abc.ABC基本上只是metaclass=abc.ABCMeta上的一个额外层。i、 eabc.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

唯一的区别是,在前一种情况下,您需要一个简单的继承,在后一种情况下,您需要指定元类。

来自What's new in Python 3.4(强调我的):

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.


相关问题:Create abstract base classes by inheritance rather than a direct invocation of ^{}

相关问题 更多 >