Python NameError:名称未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14804084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:29:16  来源:igfitidea点击:

Python NameError: name is not defined

pythonpython-3.xnameerror

提问by user1899679

I have a python script and I am receiving the following error:

我有一个 python 脚本,我收到以下错误:

Traceback (most recent call last):
  File "C:\Users\Tim\Desktop\pop-erp\test.py", line 1, in <module>  
  s = Something()
  NameError: name 'Something' is not defined

Here is the code that causes the problem:

这是导致问题的代码:

s = Something()
s.out()

class Something:
    def out():
        print("it works")

This is being run with Python 3.3.0 under Windows 7 x86-64.

这是在 Windows 7 x86-64 下使用 Python 3.3.0 运行的。

Why can't the Somethingclass be found?

为什么找不到Something类?

采纳答案by Blender

Define the class before you use it:

在使用之前定义类:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass selfas the first argument to all instance methods.

您需要self将第一个参数作为第一个参数传递给所有实例方法。

回答by user574435

You must define the class before creating an instance of the class. Move the invocation of Somethingto the end of the script.

您必须在创建类的实例之前定义类。将 的调用移动Something到脚本的末尾。

You can try to put the cart before the horse and invoke procedures before they are defined, but it will be an ugly hack and you will have to roll your own as defined here:

您可以尝试将手推车放在马之前并在定义它们之前调用程序,但这将是一个丑陋的黑客,您将不得不按照此处定义的方式推出自己的:

Make function definition in a python file order independent

使python文件顺序中的函数定义独立

回答by Tomasz Bartkowiak

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typingmodule, e.g.

请注意,有时您会希望在其自己的定义中使用类类型名称,例如在使用 Python Typing模块时,例如

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

这也会导致

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

这是因为此时尚未定义该类。解决方法是使用所谓的Forward Reference,即将类名包装在一个字符串中,即

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right