Python 3.x 如何注释返回self的Python3方法?

Python 3.x 如何注释返回self的Python3方法?,python-3.x,annotations,method-chaining,Python 3.x,Annotations,Method Chaining,函数注释: 背景:我是PyCharm用户,在Linux上拥有CPython 3.4x。我发现注释函数参数和返回类型很有帮助。当我使用这些方法时,IDE可以更好地提示我 问题:对于自链接方法,如何注释方法返回值?如果我使用类名,Python会在编译时抛出一个异常:namererror:name'X'未定义 示例代码: class X: def yaya(self, x: int): # Do stuff here pass def chained_

函数注释:

背景:我是PyCharm用户,在Linux上拥有CPython 3.4x。我发现注释函数参数和返回类型很有帮助。当我使用这些方法时,IDE可以更好地提示我

问题:对于自链接方法,如何注释方法返回值?如果我使用类名,Python会在编译时抛出一个异常:
namererror:name'X'未定义

示例代码:

class X:
    def yaya(self, x: int):
        # Do stuff here
        pass

    def chained_yaya(self, x: int) -> X:
        # Do stuff here
        return self
作为一个技巧,如果我将
X=None
放在类声明之前,它就会工作。然而,我不知道这项技术是否有不可预见的负面副作用。

你可以:

class X: 
    pass

class X:
    def yaya(self, x: int):
        # Do stuff here
        pass

    def chained_yaya(self, x: int) -> X:
        # Do stuff here
        return self
在代码中,直到类定义完成,才定义X

同样的问题:


他的解决办法是使用字符串。在您的代码中->'X'

字符串解决方案成为正式的解决方案(因此,例如PyCharm完全支持它)-请看这里:。您的问题是一个重复的问题,其中有详细的答案。