Python类型暗示方法返回当前类的列表

2024-10-01 17:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一节课是这样的:

class CareerTransition(object):
    def __init__(self, title_from: str, title_to: str)->None:
        self.title_from = title_from    # type: str
        self.title_to = title_to        # type: str

    @staticmethod
    def from_file(fname: str, verbose : bool = False)->List[CareerTransition]:
        #Do some stuff
        pass

当我尝试实例化该类时,会出现以下错误:

^{pr2}$

不能使用类型注释来引用引用当前类的泛型类型吗?为了澄清(可能不明显),它抛出了这个错误,因为类还没有定义。有办法吗?在


Tags: tofromselfnone类型objecttitleinit
2条回答

比编写@chepner所述的具体类更好的方法是使用文本__class__。整个事情看起来像这样:

@staticmethod
def from_file(fname: str, verbose : bool = False) -> List['__class__']:
    # Do some stuff
    pass

使用字符串文本作为前向引用:

@staticmethod
def from_file(fname: str, verbose : bool = False)->List['CareerTransition']:
    #Do some stuff
    pass

相关问题 更多 >

    热门问题