如何在方法参数下添加类型注释
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(函数)汽车: 未知
您可以使用引号引用同一个类:
def __add__(self,other: 'Car') :
print(f"helo {self.name} {other.name}")