Search code examples
pythonclass-method

python class method that receives an object of its class


I want to create a Square class that has method to calculate the distance from another Square. Here is how I have defined it:

class Square:
    def __init__(self, _x: int, _y: int):
        self.x = _x
        self.y = _y

    def distance(self, _other_square: Square) -> int:
        pass

The _other_square is an object of type Square. This gives me an Unresolved reference 'Square' error.

Is there a way to get around it?


Solution

  • Change the function definition to this:

    def distance(self, _other_square: 'Square') -> int:
            pass
    

    The type hint is now a str instance which will be resolved after the module has been loaded, and therefore the Square type is defined. See here for all details.