Python NameError:未定义名称

问题描述 投票:38回答:2

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

python python-3.x nameerror
2个回答
68
投票

在使用之前定义类:

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

s = Something()
s.out()

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


2
投票

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

您可以尝试将购物车放在马前并在定义之前调用程序,但这将是一个丑陋的黑客,您将必须按照此处的定义滚动您自己:

Make function definition in a python file order independent

© www.soinside.com 2019 - 2024. All rights reserved.