簡體   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