You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python数据类mypy报错:Unsupported operand types for + ("Self" and "A")原因

为什么这段代码会触发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)

错误原因

核心问题出在Self类型的语义和mypy的严格类型检查逻辑:

  • __add__方法定义的参数rhs: Self,要求参数必须是当前调用对象的具体类型实例,而非宽泛的A类实例。
  • 在add_B方法中,rhs.to_A()返回的是A类型实例,但self可能是A的子类(哪怕当前没有定义子类,mypy会考虑未来继承的可能性),此时Self代表子类类型,A实例无法满足Self的类型约束,因此mypy判定操作数类型不兼容。

解决办法

有两种常见的修复方式:

  1. 放宽__add__的参数类型约束,改为接受A类型实例:

    def __add__(self, rhs: A) -> Self:
        return type(self)(self.num + rhs.num)
    

    这样A及其子类实例都能和A实例相加,符合逻辑且通过类型检查。

  2. 若要保留Self的严格约束,需让to_A返回与self同类型的实例,可通过泛型实现:

    from typing import TypeVar
    T = TypeVar('T', bound='A')
    
    @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(type(self))
    
    @dataclass
    class B:
        num: int
    
        def to_A(self, cls: type[T]) -> T:
            return cls(self.num)
    

内容的提问来源于stack exchange,提问作者Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 03:20:19