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

为魔术方法__add__的other参数加Car类型注解时出现未定义错误怎么办?

解决Python类中魔术方法参数的类型注解未定义错误

问题场景

定义如下Car类:

class Car :
    def __init__(self,name:str,horse_power:int,fav:bool) -> None:
        self.name = name
        self.horse_power = horse_power
        self.fav = fav

    def __str__(self) -> str:
        return f"Car Name {self.name}  HorsePower {self.horse_power} Fav {self.fav}"
    
    def __add__(self,other) : 
        print(f"helo {self.name} {other.name}")

尝试为__add__方法的other参数添加Car类型注解,修改为:

def __add__(self,other:Car) : 
        print(f"helo {self.name} {other.name}")

此时VSCode的Pylance会抛出错误:

"Car" is not definedPylancereportUndefinedVariable (function) Car:
Unknown

解决方案

方法一:使用字符串字面量作为类型注解

在类定义内部编写__add__方法时,Car类的完整定义尚未完成,直接引用Car会被判定为未定义。将类型注解改为字符串形式"Car",类型检查器可以正确识别这个注解:

class Car :
    def __init__(self,name:str,horse_power:int,fav:bool) -> None:
        self.name = name
        self.horse_power = horse_power
        self.fav = fav

    def __str__(self) -> str:
        return f"Car Name {self.name}  HorsePower {self.horse_power} Fav {self.fav}"
    
    def __add__(self, other: "Car"): 
        print(f"helo {self.name} {other.name}")

方法二:导入__future__的annotations

从Python 3.7开始,导入from __future__ import annotations后,所有类型注解会被当作字符串处理,直到运行时才进行解析。这样就可以直接使用Car作为类型注解而不会报错:

from __future__ import annotations

class Car :
    def __init__(self,name:str,horse_power:int,fav:bool) -> None:
        self.name = name
        self.horse_power = horse_power
        self.fav = fav

    def __str__(self) -> str:
        return f"Car Name {self.name}  HorsePower {self.horse_power} Fav {self.fav}"
    
    def __add__(self, other: Car): 
        print(f"helo {self.name} {other.name}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 05:42:34