@奇怪的回答是正确的,但我认为它错过了
真实的
,
实际的
为什么在鸭子打字的世界里巨蟒有ABC?
抽象方法是整洁的,但在我看来,它们并不能真正填充任何尚未被duck类型所覆盖的用例。抽象基类的真正力量在于
the way they allow you to customise the behaviour of
isinstance
and
issubclass
. (
__subclasshook__
基本上是比Python更友好的API
__instancecheck__
and
__subclasscheck__
钩子。)调整内置结构以处理自定义类型是Python哲学的一部分。
Python的源代码是示例性的。
Here
是怎样
collections.Container
在标准库中定义(编写时):
class Container(metaclass=ABCMeta):
__slots__ = ()
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if any("__contains__" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
这个定义
_子章节__