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

时间:2016-08-30 20:31:30

标签: 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]

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

的内容
def idToObj(cls, elmId: int)->Action:

谢谢。

1 个答案:

答案 0 :(得分:5)

此案例在官方type hints PEP中提及:

  

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

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

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

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

在你的情况下,它将是:

def idToObj(cls, elmId: int)->'Action':
    pass  # classmethod body