注释 Python3 中静态方法的返回类型

Har*_*yte 2 python-3.x

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

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

def from_other_datastructure(json_data: str) -> MyThing:
    NameError: name 'MyThing' is not defined
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)

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

Har*_*yte 11

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

所以正确答案相当简单,而且 PyCharm 还提供了一个奖励:

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

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