抽象基类Sequence的issubclass [英] issubclass of abstract base class Sequence
问题描述
此列表显示了您使用的方法需要实现将您的类视为"序列:__getitem__
,__len__
,__contains__
,__iter__
,__reversed__
,index
和count
.那么,为什么这种最低限度的实现不起作用,即为什么issubclass(S, Sequence) is False
?
This list shows what methods you need to implement for your class to be "regarded" as Sequence: __getitem__
, __len__
, __contains__
, __iter__
, __reversed__
, index
, and count
. So why does this minimal implementation does not work, i.e. why issubclass(S, Sequence) is False
?
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背后的想法失败了,不是吗?
Is there an additional method I need to implement that I overlooked? Did I misunderstand abstract base classes? Subclassing Sequence
makes issubclass
return True
of course, but that kinda defeats the idea behind abc, doesn't it?
推荐答案
Sequence
不会实现自己的__subclasshook__
,并且所有来自Sequence
父级的__subclasshook__
实现都具有以下检查功能:
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
不过,您可以明确 register()
您的类作为Sequence
:
Sequence.register(S)
关于Sequence
不实现__subclasshook__
的原因,请参见问题16728 (其中标题最初是"collections.abc.顺序应提供__subclasshook __" ).可以通过说一个序列来概括这个问题,这取决于谁使用它的需要:
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:
许多需要序列的算法只需要
__len__
和__getitem__
. [...]collections.abc.Sequence
是一个更加丰富的界面.
Many algorithms that require a sequence only need
__len__
and__getitem__
. [...]collections.abc.Sequence
is a much richer interface.
这篇关于抽象基类Sequence的issubclass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!