Mypy:使用高级(个人)类型

2024-10-05 10:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近发现了mypy,我想用它检查代码的类型。你知道吗

我有一个Something基类:

class Something():
    ... something...

我有几个子类,它们都是Something的实例,但类型不同:

class Thing(Something)
    def __init__():
        short_name = "S"


class OtherThing(Something)
    def __init__():
        short_name = "T"

当我使用这些对象时,我通常会将它们放在一个列表中:

s1 = Thing()
s2 = OtherThing()
list_things: List[Something] = list()
list_things.append(s1)
list_things.append(s2)

但显然我做不到,mypy不承认事物和其他事物是“低级类型”的东西。你知道吗

我该怎么纠正呢?你知道吗


Tags: name类型initdefsomethinglistclassshort
1条回答
网友
1楼 · 发布于 2024-10-05 10:45:57

检查Github issue

如图所示,它是按设计的

作为解决方法,引用JukkaL's comment on github

You can often use Sequence[x] instead of List[x] to get code like your example working. This works because Sequence is covariant and doesn't let you set items in the list, unlike List[x] which is invariant and allows the mutation of the list.

相关问题 更多 >

    热门问题