【问题标题】:Annotating the return type of a staticmethod in Python3 [duplicate]在Python3中注释静态方法的返回类型[重复]
【发布时间】:2017-03-15 05:48:46
【问题描述】:

我开始使用更多 Python3 的类型支持,我希望能够注释 staticmethods 作为替代构造函数的返回类型。

下面是一个最小的例子;如果我包含它失败的注释:

def from_other_datastructure(json_data: str) -> MyThing:
    NameError: name 'MyThing' is not defined
import typing


class MyThing:
    def __init__(self, items: typing.List[int]):
        self.items = items

    @staticmethod
    def from_other_datastructure(json_data: str):
        return MyThing(
            [int(d) for d in json_data.split(',')]
        )

if __name__ == '__main__':
    s1 = MyThing([1, 2, 3])

    s2 = MyThing.from_other_datastructure("2,3,4")

那么在为类型注解定义之前如何引用一个类呢?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    发布后我立即找到了正确答案 - 前向引用可以定义为字符串。

    所以正确答案相当简单,而且 PyCharm 获得了奖励:

    @staticmethod
    def from_other_datastructure(json_data: str) -> 'MyThing':
        return MyThing(
            [int(d) for d in json_data.split(',')]
        )
    

    https://www.python.org/dev/peps/pep-0484/#forward-references

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 1970-01-01
      • 2015-01-13
      • 2014-01-26
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      相关资源
      最近更新 更多