对于在 Python 类中动态设置的属性,从 mypy 中删除错误 [英] Remove error from mypy for attributes set dynamically in a Python class

查看:26
本文介绍了对于在 Python 类中动态设置的属性,从 mypy 中删除错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using mypy to check my Python code.

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

I have a class where I set dynamically some attributes and mypy keep on complaining about it:

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种方法可以解决这个问题

Obviously, there could be 3 ways to solve the issue

  1. 忽略# 的问题 type: ignore: toto.age = 10 # type: ignore #...
  2. 使用setattr设置totoage:setattr(toto, "age", 10)
  3. 显式设置属性 (self.age = 0 ...)
  1. Ignoring the issue with # type: ignore: toto.age = 10 # type: ignore #...
  2. Using setattr to set the age of toto: setattr(toto, "age", 10)
  3. Setting the attributes explicitly (self.age = 0 ...)

然而,我正在寻找一种更优雅、更系统的课堂方式.

However, I am looking for a more elegant and systematic way at the class level.

有什么建议吗?

推荐答案

我不太了解 mypy,不知道这是否(仍然或曾经)是理想的解决方案,但是 这个问题这部分备忘单表明类似:

I don't follow mypy well enough to know whether this is (still, or ever was) the ideal work around, but this issue and this part of the cheatsheet indicate that something like:

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 抱怨(它确实如此,刚刚测试过).

Will allow you to do what you're doing without mypy complaining (which it does, just tested).

Any 可能更严格,但将在 setattr() 和传统"obj.attr = ... 上检查类型代码>调用,所以抬起头来.

Any could be more restrictive, but the types will be checked on both setattr() and "traditional" obj.attr = ... calls, so heads up.

这篇关于对于在 Python 类中动态设置的属性,从 mypy 中删除错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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