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

Python类型提示-方法返回当前类的列表,python,types,Python,Types,我有一个类似这样的类: 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(

我有一个类似这样的类:

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
当我尝试实例化该类时,出现以下错误:

Traceback (most recent call last):
  File "/Users/simon.hughes/GitHub/analytics-py-careerpathing/careerpathing/data/employment_history.py", line 8, in <module>
    class CareerTransition(object):
  File "/Users/simon.hughes/GitHub/analytics-py-careerpathing/careerpathing/data/employment_history.py", line 17, in CareerTransition
    def from_file(fname: str, verbose : bool = False)->List[CareerTransition]:
NameError: name 'CareerTransition' is not defined
回溯(最近一次呼叫最后一次):
文件“/Users/simon.hughes/GitHub/analytics py careerpating/careerpating/data/employment\u history.py”,第8行,在
类CareerTransition(对象):
文件“/Users/simon.hughes/GitHub/analytics py careerpathing/careerpathing/data/employment\u history.py”,第17行,在CareerTransition中
来自_文件的def(fname:str,verbose:bool=False)->List[CareerTransition]:
NameError:未定义名称“CareerTransition”

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

使用字符串文字作为正向引用:

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

编写@chepner所述的具体类的更好方法是使用literal
\uuuuu class\uuuu
。整个事情看起来是这样的:

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

有很多人告诉我python不做类型暗示(只是删除他们的注释)。为了节省您的时间-我也有人告诉我,这不是您键入列表的方式,而是如果您指定一个泛型列表作为类型提示-请参见此处:brilliant。你不会相信有多少人试图告诉我python不支持类型提示,或者我输入了错误的列表(List)。@Simon总共有两个人这么说。:)好的,没错。那还是人:)人还是人!:)我们可以就此达成一致:)