[英]Type hint for class method return error - name is not defined?
The following class has a class method create()
, which as a type hint for return type, for creating an instance of the class.下面的 class 有一个 class 方法
create()
,它作为返回类型的类型提示,用于创建 class 的实例。
class X:
@classmethod
def create(cls) -> X:
pass
However, it got the following error?但是,它得到了以下错误?
NameError: name 'X' is not defined
NameError:名称“X”未定义
The name X
doesn't exist until the class is fully defined.在完全定义 class 之前,名称
X
不存在。 You can fix this by importing a __future__
feature called annotations
.您可以通过导入名为
annotations
的__future__
功能来解决此问题。 Just put this at the top of your file.只需将其放在文件的顶部即可。
from __future__ import annotations
This wraps all annotations in quotation marks, to suppress errors like this.这会将所有注释用引号括起来,以抑制这样的错误。 It's the same as doing this
和这样做是一样的
class X:
@classmethod
def create(cls) -> 'X': # <-- Note the quotes
pass
but automatically.但自动。 This will be the default behavior in some future Python version (originally, it was going to be 3.10, but it's been pushed back due to compatibility issues), but for now the import will make it behave the way you want.
这将是未来 Python 版本(最初是 3.10,但由于兼容性问题而被推迟)中的默认行为,但现在导入将使其行为符合您的要求。
The future import was added in Python 3.7.在 Python 3.7 中添加了未来的导入。 If you're on an older version of Python, you'll have to manually wrap the types in strings, as I did in the example above.
如果您使用的是旧版本的 Python,则必须手动将类型包装在字符串中,就像我在上面的示例中所做的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.