mypy 错误:Python 数据类中 +(“Self”和“A”)[运算符] 不受支持的操作数类型

问题描述 投票:0回答:1

我正在开发一个依赖严格类型提示的项目。我正在处理的最小代码示例将返回此 mypy 错误:

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)

有人可以向我解释为什么会出现这种情况吗?

python types mypy
1个回答
1
投票

在您的班级

A
中,您定义只能添加
Self
Self
。您的
add_B
方法尝试添加
Self
A

想象

A2
的子类
A
。现在
add_B
将尝试将使用
A
构建的
to_A
对象传递到需要
A2
的方法中。这是禁止的,因为
A
不是
A2
的子类。

这意味着根本不可能对

A
进行子类化。 Mypy 可能会报告这一点,因为它无法安全地知道不存在子类,或者永远不会有
A
的子类。

修复方法很明显:仅接受

A
替换
rhs
中的
__add__

    ...

    def __add__(self, rhs: 'A') -> Self:
        ...
© www.soinside.com 2019 - 2024. All rights reserved.