mypy:“__getitem__"的签名;与超类型“序列"不兼容 [英] mypy: Signature of "__getitem__" incompatible with supertype "Sequence"

查看:34
本文介绍了mypy:“__getitem__"的签名;与超类型“序列"不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承自 MutableSequence 的类,如下所示:

I have a class that inherits from MutableSequence like this:

class QqTag(MutableSequence):
    def __init__(self):
        self._children = []
    def __getitem__(self, idx: int) -> 'QqTag':
        return self._children[idx]

mypy 抱怨 __getitem__"的签名与超类型Sequence"不兼容.

Sequence中,该方法定义为:

@abstractmethod
def __getitem__(self, index):
    raise IndexError

那么,问题是什么?为什么 mypy 对我的实现不满意?

So, what's the problem and why mypy isn't happy with my implementation?

推荐答案

正如评论中提到的,也可以传递一个 typeof 切片.即,将 idx: int 更改为 idx: Union[int, slice].

As mentioned in comments, a typeof slice can also be passed. Ie, change idx: int to idx: Union[int, slice].

这会让 mypy 开心(至少在我的机器上;):

This will make mypy happy (at least on my machine ;):

class QqTag(MutableSequence):
    def __init__(self):
        self._children = []

    def __getitem__(self, idx: Union[int, slice]) -> 'QqTag':
        return self._children[idx]

这篇关于mypy:“__getitem__"的签名;与超类型“序列"不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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