如何正确地向 Mixin 类添加类型提示? [英] How do I correctly add type-hints to Mixin classes?
问题描述
考虑以下示例.这个例子是人为的,但在一个可运行的例子中说明了这一点:
Consider the following example. The example is contrived but illustrates the point in a runnable example:
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))
执行后将给出以下输出:
When executed this will give the following output:
12
20
代码有效.
但是在其上运行 mypy
会产生以下错误:
But running mypy
on it, yields the following errors:
example.py:4: error: "MultiplicatorMixin" has no attribute "value"
example.py:10: error: "AdditionMixin" has no attribute "value"
我明白为什么 mypy 会给出这个结果.但是 mixin 类从不单独使用.它们总是用作额外的超类.
I understand why mypy gives this result. But the mixin classes are never used by themselves. They are always used as additional superclasses.
对于上下文,这是一种已在现有应用程序中使用的模式,我正在添加类型提示.在这种情况下,错误是误报.我正在考虑使用 mixin 重写该部分,因为我不是特别喜欢它,同样可以通过重新组织类层次结构来完成.
For context, this is a pattern which has been used in an existing application and I am in the process of adding type-hints. And in this case, the errors are false-positives. I am thinking about rewriting the part using the mixins as I don't particularly like it and the same could probably be done with reorganising the class hierarchy.
但我仍然想知道如何正确暗示这样的事情.
But I still would like to know how something like this could be properly hinted.
推荐答案
我已经在我的机器上测试过了,希望它也适用于你:
I've tested it on my machine, hope it will also work for you:
class MultiplicatorMixin:
value = None # type: int
def multiply(self, m: int) -> int:
return self.value * m
class AdditionMixin:
value = None # type: int
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))
这篇关于如何正确地向 Mixin 类添加类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!