issubclass of abstract base class Sequence

后端 未结 1 599
灰色年华
灰色年华 2020-12-21 02:53

This list shows what methods you need to implement for your class to be \"regarded\" as Sequence: __getitem__, __len__, __contains__,

相关标签:
1条回答
  • 2020-12-21 03:37

    Use the source, Luke!

    Sequence does not implement its own __subclasshook__, and all the implementations of __subclasshook__ from the parents of Sequence have checks like this:

    class Iterable:
        ...
    
        @classmethod
        def __subclasshook__(cls, C):
            if cls is Iterable:  # <<<<
                if _hasattr(C, "__iter__"):
                    return True
            return NotImplemented
    

    You can however explicitly register() your class as a Sequence:

    Sequence.register(S)
    

    As for the reason why Sequence does not implement __subclasshook__, see issue 16728 (which title was initially "collections.abc.Sequence shoud provide __subclasshook__"). The issue can be summarized by saying that a sequence can be many things, depending on the needs of who uses it:

    Many algorithms that require a sequence only need __len__ and __getitem__. [...] collections.abc.Sequence is a much richer interface.

    0 讨论(0)
提交回复
热议问题