抽象基类Sequence的issubclass [英] issubclass of abstract base class Sequence

查看:91
本文介绍了抽象基类Sequence的issubclass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此列表显示了您使用的方法需要实现将您的类视为"序列:__getitem____len____contains____iter____reversed__indexcount.那么,为什么这种最低限度的实现不起作用,即为什么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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆