当我不小心将变量更改为不同的数据类型时,我想使用 Mypy 来警告我。
但似乎 Mypy 忽略了 __init__
中发生的任何事情我的测试课。
它还忽略对象属性对不同数据类型的更改。
最小复制器:
class Foo:
blah: int
def __init__(self):
self.blah = 'asdf'
Mypy reports no issues对于此代码。我错过了什么吗?
最佳答案
mypy
忽略任何 def
的正文没有类型注释的语句。注释任何参数或使用 --check-untyped-defs
flag原因 mypy
检查 __init__
并拒绝不正确的分配。
class Foo:
blah: int
blub: int
# annotated parameter `blub` and/or return `->` trigger inspection
def __init__(self, blub: int = 42) -> None:
self.blah = 'asdf' # error: Incompatible types in assignment (expression has type "str", variable has type "int")
self.blub = blub
关于python - Mypy 是否忽略构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62615599/