Home > Enterprise >  Abstract class Container - Python
Abstract class Container - Python

Time:11-04

I am trying to understand why any class that has the __contains__ method becomes an instance of the Container abstract class. I am getting a little confused because the correct way should be like this class dumb(Container): and define your own __contains__ method.

It supposes to be because of duck typing but where is the duck typing there?

CodePudding user response:

Classes are able to customize isinstance checks by implementing __subclasshook__. 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) ```

CodePudding user response:

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.

  • Related