Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python名称错误:未定义名称_Python_Python 3.x_Nameerror - Fatal编程技术网

Python名称错误:未定义名称

Python名称错误:未定义名称,python,python-3.x,nameerror,Python,Python 3.x,Nameerror,我有一个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 这是在Windows7x86-64下使用Python 3.3.0运行的 为什么找不到Something类?在创

我有一个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
这是在Windows7x86-64下使用Python 3.3.0运行的


为什么找不到
Something
类?

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

您可以尝试本末倒置,并在定义过程之前调用过程,但这将是一个难看的黑客行为,您必须按照此处的定义进行操作:


在使用类之前定义它:

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

s = Something()
s.out()

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

请注意,有时您需要在自己的定义中使用类类型名称,例如在使用Python模块时,例如

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right
这也将导致

NameError: name 'Tree' is not defined
这是因为此时尚未定义该类。 解决方法是使用所谓的,即用字符串包装类名,即

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

太好了,谢谢!我本想把self也包括在内,但当我很快写下这个简短的例子时就忘了。总是有
@staticmethod
@classmethod
,只是为了让事情有趣:-P@mgilson为了更有趣,
self
将与
@classmethod
一起使用,这只是一个误称(应该称为
cls
)。@delnan——是的,当然是正确的。也许我不应该在其中添加
@classmethod
,但我只是想暗示您可以更改第一个参数(或者即使它被传递)。我意识到变量名
self
并没有什么神奇之处(除了一个非常根深蒂固的惯例,无论如何都不应该被违反)。@mgilson我不是说你错了。我不怀疑你知道这一切。这只是另一个有趣的事实:-)这个问题的解决方案是在定义类和函数之后调用它们。Python没有任何方法来转发声明类或方法,因此唯一的选择是将函数调用放在程序的末尾,而不是开始。另一个选项是将方法放在文件顶部的导入库中,这些库总是首先被调用。
class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right