gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:40:46 24 4
gpt4 key购买 nike

在 Python 3.4+ 中,我们可以这样做

class Foo(abc.ABC):
...

或者我们可以做

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

两者之间有什么我应该注意的区别吗?

最佳答案

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

唯一的区别是前者需要简单的继承,后者需要指定元类。

来自 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 __metaclass__

关于python - 使用 ABC 和 ABCMeta 有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com