Dunder 方法其他参数类型

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

如何在方法参数下添加类型注释

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 dunder 方法中,当我尝试指定其他参数的类型时

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

在 VScode 中我收到错误

“汽车”未定义PylancereportUndefinedVariable(函数)汽车: 未知

python
1个回答
0
投票

您可以使用引号引用同一个类:

def __add__(self,other: 'Car') : 
        print(f"helo {self.name} {other.name}")
© www.soinside.com 2019 - 2024. All rights reserved.