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

前端 未结 5 625
抹茶落季
抹茶落季 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 07:56

    If you only care about fixing the NameError: name 'Position' is not defined, you can either specify the class name as a string:

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

    Or if you use Python 3.7 or higher, add the following line to the top of your code (just before the other imports)

    from __future__ import annotations
    

    However, if you also want this to work for subclasses, and return the specific subclass, you need to use a Generic class, by define a TypeVar.

    What is slightly uncommon is that the TypeVar is bound to the type of self. Basically, this typing hinting tells the type checker that the return type of __add__() and copy() are the same type as self.

    from __future__ import annotations
    
    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: T, other: Position) -> T:
            return type(self)(self.x + other.x, self.y + other.y)
        
        def copy(self: T) -> T:
            return type(self)(self.x, self.y)
    

提交回复
热议问题