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

Sim*_*mon 7 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(fname: str, verbose : bool = False)->List[CareerTransition]:
        #Do some stuff
        pass
Run Code Online (Sandbox Code Playgroud)

当我尝试实例化该类时,我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

是否不可能使用类型注释来引用引用当前类的泛型类型?澄清(因为它可能不是很明显)它正在抛出该错误,因为该类尚未定义.有没有解决的办法?

mel*_*bic 8

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

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


che*_*ner 7

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

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

  • 好的.那还是人:) (2认同)