【发布时间】:2019-01-26 13:25:37
【问题描述】:
考虑以下示例。该示例是人为设计的,但在一个可运行的示例中说明了这一点:
class MultiplicatorMixin:
def multiply(self, m: int) -> int:
return self.value * m
class AdditionMixin:
def add(self, b: int) -> int:
return self.value + b
class MyClass(MultiplicatorMixin, AdditionMixin):
def __init__(self, value: int) -> None:
self.value = value
instance = MyClass(10)
print(instance.add(2))
print(instance.multiply(2))
执行时会给出以下输出:
12
20
代码有效。
但是在上面运行mypy,会产生以下错误:
example.py:4: error: "MultiplicatorMixin" has no attribute "value"
example.py:10: error: "AdditionMixin" has no attribute "value"
我明白为什么 mypy 会给出这个结果。但是 mixin 类从不单独使用。它们总是用作额外的超类。
对于上下文,这是一种已在现有应用程序中使用的模式,我正在添加类型提示。在这种情况下,错误是误报。我正在考虑使用 mixins 重写该部分,因为我不是特别喜欢它,并且可能通过重新组织类层次结构来完成相同的操作。
但我仍然想知道如何正确提示这样的事情。
【问题讨论】:
-
类型提示是否导致
mypy错误?还是在没有类型提示的情况下仍然会出现这些错误?如果是这样,那么类型提示与问题无关,我认为您的问题应该是“如何处理mypy中缺少属性错误?” -
@JonathonReinhart 我不明白你的意思。如果我删除类型提示,那么
mypy将不再做任何事情(假设所有内容都是Any类型)。所以我看不出这样做的意义。 FWIW,我删除了类型提示并再次运行它,正如预期的那样,错误消失了(因为一切都是Any)。 -
对不起,我不熟悉 mypy,并认为它只是一个 pylint 样式的检查器。不过,我觉得这与类型提示本身没有任何关系,只是 mypy 工具的一个限制。
-
绝对有可能。但在那种情况下,最好了解这种情况下的任何最佳实践。我可以撒一些
# type: ignorecmets,但我想看看在完全禁用类型检查之前是否有替代方法。
标签: python oop type-hinting mypy python-typing