2016-08-30 81 views
2

我想指定(作爲類型提示)當前定義的類型作爲方法的返回類型。(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: 

謝謝。

回答

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