关于python:抽象基类Sequence的issubclass

issubclass of abstract base class Sequence

此列表显示需要实现哪些方法才能将类"视为"序列:__getitem____len____contains____iter____reversed__indexcount。那么,为什么这种最小的实现不起作用,即为什么issubclass(S, Sequence) is False

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from collections import *


class S(object):
    def __getitem__(self, item):
        raise IndexError

    def __len__(self):
        return 0

    def __contains__(self, item):
        return False

    def __iter__(self):
        return iter(())

    def __reversed__(self):
        return self

    def index(self, item):
        raise IndexError

    def count(self, item):
        return 0


issubclass(S, Iterable)   # True  :-)
issubclass(S, Sized)      # True  :-)
issubclass(S, Container)  # True  :-)
issubclass(S, Sequence)   # False :-(

是否有其他方法需要实现我忽略的方法?我是否误解了抽象基类?子类化Sequence使issubclass返回True当然,但这有点破坏了ABC的思想,不是吗?


使用源,卢克!

Sequence的父母那里,是否没有实施自己的__subclasshook____subclasshook__的所有实施情况?

1
2
3
4
5
6
7
8
9
class Iterable:
    ...

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

你的班级可以解释为

ZZU1

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

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