代码之家  ›  专栏  ›  技术社区  ›  Jean-Francois T.

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

  •  5
  • Jean-Francois T.  · 技术社区  · 7 年前

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

    我有一个类,在这个类中我动态地设置了一些属性和 我的孩子 继续抱怨:

    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 设置 age 属于 toto 以下内容: setattr(toto, "age", 10)
    3. 显式设置属性( self.age = 0 …)

    然而,我在寻找一个更优雅和系统的方式在班级一级。

    有什么建议吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   jedwards    7 年前

    我跟不上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
    

    会让你做你正在做的事情,而不会有我的抱怨(它做了,只是测试)。

    Any 可能更严格,但类型将在 setattr() 和“传统” obj.attr = ... 打电话,所以要当心。