(Python类型提示)如何指定当前定义的类型作为方法的返回类型?
问题描述:
我想指定(作为类型提示)当前定义的类型作为方法的返回类型。(Python类型提示)如何指定当前定义的类型作为方法的返回类型?
下面是一个例子:
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:
谢谢。
答
这种情况在官方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