简体   繁体   English

抽象类容器 - Python

[英]Abstract class Container - Python

I am trying to understand why any class that has the __contains__ method becomes an instance of the Container abstract class.我试图理解为什么任何具有__contains__方法的类都会成为 Container 抽象类的实例。 I am getting a little confused because the correct way should be like this class dumb(Container): and define your own __contains__ method.我有点困惑,因为正确的方法应该像这个class dumb(Container):并定义自己的__contains__方法。

It supposes to be because of duck typing but where is the duck typing there?应该是因为鸭子打字,但鸭子打字在哪里?

Classes are able to customize isinstance checks by implementing __subclasshook__ .类可以通过实现__subclasshook__来自定义isinstance检查。 Many classes will choose to look at properties of the instance to determine the type rather than relying on the inheritance hierarchies许多类会选择查看实例的属性来确定类型而不是依赖继承层次结构

For example, this is how Container is implemented例如, 这是容器的实现方式

class Container(metaclass=ABCMeta): __slots__ = () @abstractmethod def __contains__(self, x): return False @classmethod def __subclasshook__(cls, C): if cls is Container: return _check_methods(C, "__contains__") return NotImplemented __class_getitem__ = classmethod(GenericAlias) ```

If it walks like a duck and it quacks like a duck, then it must be a duck.如果它走路像鸭子,叫起来像鸭子,那它一定是鸭子。

Duck typing is the idea that, in some cases, an object can be defined moreso by its functionality than by its class designation.鸭子类型的想法是,在某些情况下,一个对象可以通过它的功能而不是它的类名称来定义。 By including a __contains__ method, the implication is that the object functions as a container.通过包含__contains__方法,这意味着该对象用作容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM