Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I have the following code in python 3:

class Position:

    def __init__(self, x: int, y: int):

        self.x = x

        self.y = y

    def __add__(self, other: Position) -> Position:

        return Position(self.x + other.x, self.y + other.y)

But my editor (PyCharm) says that the reference Position can not be resolved (in the __add__ method). How should I specify that I expect the return type to be of type Position?

1 Answer

0 votes
by (106k points)

To specify that the return type of a method is the same as the class you can use the below-mentioned code:-

from typing import TypeVar 

T = TypeVar('T', bound='Position') 

class Position: 

def __init__(self, x: int, y: int): 

self.x = x 

self.y = y 

def __add__(self, other: T) -> T: 

return Position(self.x + other.x, self.y + other.y)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked May 21, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
0 answers
asked Jan 5, 2021 in Python by spec300 (120 points)

Browse Categories

...