How do I type hint a method with the type of the enclosing class?

前端 未结 5 595
抹茶落季
抹茶落季 2020-11-21 07:15

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,          


        
5条回答
  •  渐次进展
    2020-11-21 08:00

    Specifying the type as string is fine, but always grates me a bit that we are basically circumventing the parser. So you better not misspell any one of these literal strings:

    def __add__(self, other: 'Position') -> 'Position':
        return Position(self.x + other.x, self.y + other.y)
    

    A slight variation is to use a bound typevar, at least then you have to write the string only once when declaring the typevar:

    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)
    

提交回复
热议问题