Python名称错误:未定义名称

2024-05-20 06:16:49 发布

您现在位置: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")

这是在Windows7x86-64下使用Python 3.3.0运行的

为什么找不到Something


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

必须在创建类的实例之前定义该类。将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

在使用类之前定义它:

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

s = Something()
s.out()

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

相关问题 更多 >