我正在使用 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 种方法可以解决这个问题
- 忽略
# type: ignore
的问题:toto.age = 10 # type: ignore #...
- 使用
setattr
设置toto
的age
:setattr(toto, "age", 10)
- 显式设置属性(
self.age = 0
...)
但是,我正在寻找一种更优雅、更系统的类级别方法。
有什么建议吗?
最佳答案
我对 mypy 的了解不够好,不知道这是否(仍然是,或者曾经是)理想的解决方法,但是 this issue和 this 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/