issubclass of abstract base class Sequence
此列表显示需要实现哪些方法才能将类"视为"序列:
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 :-( |
是否有其他方法需要实现我忽略的方法?我是否误解了抽象基类?子类化
使用源,卢克!
从
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
Many algorithms that require a sequence only need
__len__ and__getitem__ . [...]collections.abc.Sequence is a much richer interface.