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

前端 未结 5 608
抹茶落季
抹茶落季 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:59

    When a string-based type hint is acceptable, the __qualname__ item can also be used. It holds the name of the class, and it is available in the body of the class definition.

    class MyClass:
        @classmethod
        def make_new(cls) -> __qualname__:
            return cls()
    

    By doing this, renaming the class does not imply modifying the type hints. But I personally would not expect smart code editors to handle this form well.

提交回复
热议问题