繁体   English   中英

Mypy:属性设置器赋值中的不兼容类型

[英]Mypy: Incompatible types in assignment for property setter

我想在 mypy 中使用property setter 属性 getter 和 setter 的类型不同:

from typing import List, Iterable

class Foo:
    @property
    def x(self) -> List[int]:
        ...

    @x.setter
    def x(self, new_x: Iterable[int]):
        ...

foo = Foo()
foo.x = (1, 2, 3) # error: Incompatible types in assignment (expression has type "Tuple[int, int, int]", variable has type "List[int]")

我该如何处理这个错误?

Mypy 抱怨类型不兼容,因为 Tuple 有不同的签名:

# For tuples, we specify the types of all the elements
x: Tuple[int, str, float] = (3, "yes", 7.5)

在 setter 和 getter 的情况下,如果您只是将 setter 的输入参数分配给类变量,则类型应该相同。 Iterable[int] 和 Tuple[int,int,int] 是不同的类型,因为在这种情况下 tuple 是不可变对象并且有 3 个元素。

处理此错误的方法是在设置为 foo.x 之前将元组转换为列表:

foo.x = list((1,2,3))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM