简体   繁体   English

class 方法返回错误的类型提示 - 名称未定义?

[英]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.

相关问题 在嵌套 class 的方法中键入提示? - type hint in method for a nested class? 类型提示返回 NameError: name 'datetime' not defined - type hint returns NameError: name 'datetime' not defined 类型提示工厂方法的返回值? - type hint for return value of a factory method? Python 子 class 中方法返回的覆盖类型提示,没有重新定义方法签名 - Python overriding type hint on a method's return in child class, without redefining method signature 基于子类的 Base class 方法的类型提示 - Type hint of Base class method based on Subclass 在 Django 中使用类型提示 Any - NameError: name &#39;Any&#39; is not defined - Using type hint Any in Django - NameError: name 'Any' is not defined 如何键入带有封闭 class 类型的提示方法? - How do I type hint a method with the type of the enclosing class? 如何使用 class 属性作为 class 内部方法的类型提示? - How to use a class attribute as the type hint for a method inside the class? 引号中的mypy显式类型提示仍给出未定义的错误 - mypy explicit type hint in quotes still gives not defined error 先前定义的类方法上的 Name Error 和应该存在的 Index 上的 IndexError - Name Error on a class method previously defined and IndexError on an Index that should exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM