[英]Python Type Hinting - Method Returns a List of the Current Class
I have a class that looks like this: 我有一个看起来像这样的课程:
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
I get this error when I try to instantiate that class: 当我尝试实例化该类时,我收到此错误:
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
Is it not possible to use type annotations to refer to generic types that reference the current class? 是否不可能使用类型注释来引用引用当前类的泛型类型? To clarify (as it may not be obvious) it's throwing that error as the class is not defined yet. 澄清(因为它可能不是很明显)它正在抛出该错误,因为该类尚未定义。 Is there a way around this? 有没有解决的办法?
Use a string literal for a forward reference: 使用字符串文字作为前向引用:
@staticmethod
def from_file(fname: str, verbose : bool = False)->List['CareerTransition']:
#Do some stuff
pass
An even nicer way then writing the concrete class as stated by @chepner is to use the literal __class__
. 然后编写@chepner所述的具体类更好的方法是使用文字__class__
。 The whole thing would look like this: 整件事情看起来像这样:
@staticmethod
def from_file(fname: str, verbose : bool = False) -> List['__class__']:
# Do some stuff
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.