英文:
mypy error: Unsupported operand types for + ("Self" and "A") [operator] in Python dataclasses
问题
我正在研究一个依赖于严格类型提示的项目。我正在处理的最小代码示例将返回此mypy错误:
error.py:15: error: 不支持的操作数类型+(“Self”和“A”)[operator]
return self + rhs.to_A()
^~~~~~~~~~
可以有人解释一下为什么会出现这种情况吗?
英文:
I'm working on a project that relies on strict type hinting. The minimal code example that I'm working on will return this mypy error:
error.py:15: error: Unsupported operand types for + ("Self" and "A") [operator]
return self + rhs.to_A()
^~~~~~~~~~
from __future__ import annotations
from dataclasses import dataclass
from typing_extensions import Self
@dataclass
class A:
num: int = 0
def __add__(self, rhs: Self) -> Self:
return type(self)(self.num + rhs.num)
def add_B(self, rhs: B) -> Self:
return self + rhs.to_A()
@dataclass
class B:
num: int
def to_A(self) -> A:
return A(self.num)
Can someone explain to me why this is the case?
答案1
得分: 1
在你的类A
中,你定义了只能添加Self
和Self
。你的add_B
方法试图添加Self
和A
。
想象一个A
的子类A2
。现在,add_B
将尝试将它使用to_A
构建的A
对象传递给一个期望A2
的方法。这是被禁止的,因为A
不是A2
的子类。
这意味着根本不可能对A
进行子类化。Mypy可能会报告这个问题,因为它不能安全地知道是否有子类,或者是否将来会有A
的子类。
修复方法很明显:在__add__
中只接受A
作为rhs
。
...
def __add__(self, rhs: 'A') -> Self:
...
英文:
In your class A
you define that you can only add Self
and Self
. Your add_B
method tries to add Self
and A
.
Imagine a subclass A2
of A
. Now add_B
will try to pass the A
object it built with to_A
into a method that expects an A2
. That is forbidden, because A
is not a subclass of A2
.
That means it is impossible to subclass A
at all. Mypy probably reports this because it cannot safely know that there are no subclasses or that there will never be subclasses of A
.
The fix is obvious: accept just A
for rhs
in __add__
.
...
def __add__(self, rhs: 'A') -> Self:
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论