Python NameError:未定义名称

2024-05-20 19:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

下面是导致问题的代码:

s = Something()
s.out()

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

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

为什么找不到Something类?


Tags: 脚本mosterp错误calloutpopusers
3条回答

在使用类之前定义它:

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

s = Something()
s.out()

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

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

你可以尝试本末倒置,在定义程序之前调用它们,但这将是一个丑陋的黑客行为,你将不得不按照这里的定义自行操作:

Make function definition in a python file order independent

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

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

这也会导致

NameError: name 'Tree' is not defined

这是因为目前还没有定义类。 解决方法是使用所谓的Forward Reference,即用字符串包装类名,即

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

相关问题 更多 >