繁体   English   中英

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

[英](Python type hints) How to specify type being currently defined as the returned type from a method?

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

这是一个例子:

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:

谢谢。

在官方类型提示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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM