(Python类型提示)如何指定当前定义为方法的返回类型的类型?

rad*_*duw 2 python type-hinting

我想指定(作为类型提示)当前定义的类型作为方法的返回类型.

这是一个例子:

class Action(Enum):
    ignore = 0
    replace = 1
    delete = 2

    @classmethod
    # I would like something like
    # def idToObj(cls, elmId: int)->Action:
    # but I cannot specify Action as the return type
    # since it would generate the error
    # NameError: name 'Action' is not defined
    def idToObj(cls, elmId: int):
        if not hasattr(cls, '_idToObjDict'):
            cls._idToObjDict = {}
            for elm in list(cls):
                cls._idToObjDict[elm.value] = elm

        return cls._idToObjDict[elmId]
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望指定类似的东西

def idToObj(cls, elmId: int)->Action:
Run Code Online (Sandbox Code Playgroud)

谢谢.

Łuk*_*ski 5

官方类型提示PEP中提到了这种情况:

当类型提示包含尚未定义的名称时,该定义可以表示为字符串文字,稍后要解决.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,我们写道:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right
Run Code Online (Sandbox Code Playgroud)

在你的情况下它将是:

def idToObj(cls, elmId: int)->'Action':
    pass  # classmethod body
Run Code Online (Sandbox Code Playgroud)