【问题标题】:How to annotate a Python3 method that returns self?如何注释返回自我的Python3方法?
【发布时间】:2015-01-13 06:31:30
【问题描述】:

函数注释: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 放在类声明之前,它会起作用。但是,我不知道这种技术是否会产生不可预见的负面副作用。

【问题讨论】:

  • 您的问题与this one 重复,其中有详细答案。

标签: python-3.x annotations method-chaining


【解决方案1】:

你可以这样做:

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'

【讨论】:

猜你喜欢
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 2022-12-12
  • 1970-01-01
  • 2021-06-06
  • 2014-01-26
  • 1970-01-01
相关资源
最近更新 更多