[英]Remove error from mypy for attributes set dynamically in a Python class
我正在使用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種方法來解決這個問題
toto.age = 10 # type: ignore #...
的問題# type: ignore
: toto.age = 10 # type: ignore #...
setattr
設置toto
的age
: setattr(toto, "age", 10)
self.age = 0
...) 但是,我在課堂上尋找更優雅,更系統的方式。
有什么建議嗎?
我沒有足夠好地跟蹤mypy以了解這是否(仍然或曾經是)理想的工作,但是這個問題和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 = ...
調用上檢查,所以抬頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.