Search code examples
pythonpython-typing

Dunder method other param type


how to add type annotations dunder method params

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}")

In add dunder method when i tries to specify type for other param

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

In VScode i am getting error

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


Solution

  • You can reference the same class using quotation marks:

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

    You can find more cool solutions here