python - 从 mypy 中删除在 Python 类中动态设置的属性的错误

标签 python mypy

我正在使用 mypy 检查我的 Python 代码。

我有一个类,我在其中动态设置了一些属性,mypy 一直提示它:

error:"Toto" has no attribute "age"

这是我的代码:

class Toto:
    def __init__(self, name:str) -> None:
        self.name = name
        for attr in ['age', 'height']:
            setattr(self, attr, 0)


toto = Toto("Toto")
toto.age = 10  # "Toto" has no attribute "age" :(

显然,有 3 种方法可以解决这个问题

  1. 忽略 # type: ignore 的问题:toto.age = 10 # type: ignore #...
  2. 使用setattr设置totoage:setattr(toto, "age", 10)
  3. 显式设置属性(self.age = 0 ...)

但是,我正在寻找一种更优雅、更系统的类级别方法。

有什么建议吗?

最佳答案

我对 mypy 的了解不够好,不知道这是否(仍然是,或者曾经是)理想的解决方法,但是 this issuethis part of the cheatsheet表明是这样的:

from typing import Any

class Toto:
    def __init__(self, name:str) -> None:
        self.name = name
        for attr in ['age', 'height']:
            setattr(self, attr, 0)

    def __setattr__(self, name:str, value:Any):
        super().__setattr__(name, value)

toto = Toto("Toto")
toto.age = 10

将允许您在没有 mypy 提示的情况下做您正在做的事情(它所做的,刚刚测试过)。

Any可能会更严格,但类型将在 setattr() 上进行检查和“传统”obj.attr = ...电话,所以请注意。

关于python - 从 mypy 中删除在 Python 类中动态设置的属性的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50889677/

相关文章:

python http状态码

python - 计算 A* 寻路算法的执行时间时,Python 列表中缺少项目

python - 什么 Python 类型注释来表示泛型类型类

python - 为什么 mypy `cast` 只在某些时候有效?

python - 数据类字段的工厂函数

python - Pygame 图像在没有正确输入的情况下移动

python - 从数据框或系列的 Pandas 输出中删除名称、数据类型

python - 带参数的装饰器的 MyPy 错误

python - 在 python 中填充列表

python - mypy: "__setitem__"的签名与父类(super class)型 "list"不兼容