如何注释返回 self 的 Python3 方法?

kev*_*rpe 5 annotations method-chaining python-3.x

函数注释:PEP-3107

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

问题:对于自链方法,如何注释方法返回值?如果我使用类名,Python 会在编译时抛出异常:NameError: name 'X' is not defined

示例代码:

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

    def chained_yaya(self, x: int) -> X:
        # Do stuff here
        return self
Run Code Online (Sandbox Code Playgroud)

作为一个技巧,如果我把X = None它放在类声明之前,它就可以工作。但是,我不知道这种技术是否有不可预见的负面影响。

The*_*le1 4

从 Python 3.11 开始,您将能够使用Self注释返回类型:

from typing import Self


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

    def chained_yaya(self, x: int) -> Self:
        # Do stuff here
        return self
Run Code Online (Sandbox Code Playgroud)