我正在检查hasattr是否有一个对象有属性。如果它存在,我会赋值它。然而,mypy仍然抱怨has no attribute。我如何帮助mypy记住这个属性的存在?
MVCE
另存为example.py
from typing import Any
class MakeNoiseMixin:
def make_noise(self):
if isinstance(self, Cat) or hasattr(self, "cat"):
cat = self if isinstance(self, Cat) else self.cat
cat.meow()
else:
print("zZ")
class Cat(MakeNoiseMixin):
def meow(self):
print("meow!")
class Dog(MakeNoiseMixin):
...
class Human(MakeNoiseMixin):
def __init__(self, cat):
self.cat = cat
felix = Cat()
felix.make_noise()
tom = Dog()
tom.make_noise()
felix_owner = Human(felix)
felix_owner.make_noise()运行:
$ python example.py
meow!
zZ
meow!
$ example.py --check-untyped-defs
example.py:4: error: "MakeNoiseMixin" has no attribute "cat"发布于 2021-05-19 16:05:08
这不是正在寻找的答案,而是将其作为一种方法放在这里。期待看到其他答案。
顺便说一句,定义一个variable annotation不会产生一个新的表列,但是即使它是一个类级别的变量,而不是模型字段的实例,Django也会更清楚。
from typing import Any
class MakeNoiseMixin:
cat: Any
def make_noise(self):
if isinstance(self, Cat) or hasattr(self, 'cat'):
cat = self if isinstance(self, Cat) else self.cat
cat.meow()
else:
print("zZ")
class Cat(MakeNoiseMixin):
def meow(self):
print("meow!")
felix = Cat()
felix.make_noise()$ mypy example.py --check-untyped-defs
Success: no issues found in 1 source filehttps://stackoverflow.com/questions/67597338
复制相似问题