猿问

Python 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

这是导致问题的代码:


s = Something()

s.out()


class Something:

    def out():

        print("it works")

这是在Windows 7 x86-64下与Python 3.3.0一起运行的。


为什么找不到Something班级?


一只甜甜圈
浏览 1323回答 3
3回答

holdtom

在使用它之前定义类:class Something:&nbsp; &nbsp; def out(self):&nbsp; &nbsp; &nbsp; &nbsp; print("it works")s = Something()s.out()您需要self将第一个参数传递给所有实例方法。

GCT1015

解决此问题的方法是在定义类和函数后调用它们。Python没有任何方法来转发声明的类或方法,因此唯一的选择是将函数调用放在程序的末尾而不是开始。另一种选择是将您的方法放在文件顶部的导入库中,该库总是首先被调用。
随时随地看视频慕课网APP

相关分类

Python
我要回答