函数注释: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
作为一个技巧,如果我输入
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 直到类定义完成后才被定义。
同样的问题:putting current class as return type annotation
他的解决方案是使用字符串。在您的代码中 -> 'X'
关于python-3.x - 如何注释返回 self 的 Python3 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26954173/