簡體   English   中英

從mypy中刪除Python類中動態設置的屬性的錯誤

[英]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種方法來解決這個問題

  1. 忽略toto.age = 10 # type: ignore #...的問題# type: ignoretoto.age = 10 # type: ignore #...
  2. 使用setattr設置totoagesetattr(toto, "age", 10)
  3. 顯式設置屬性( 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM