Python中的函数未定义错误

52 投票
5 回答
316124 浏览
提问于 2025-04-16 17:33

我正在尝试在Python中定义一个基本的函数,但每次运行一个简单的测试程序时,总是会出现以下错误;

>>> pyth_test(1, 2)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    pyth_test(1, 2)
NameError: name 'pyth_test' is not defined

这是我用来定义这个函数的代码;

def pyth_test (x1, x2):
    print x1 + x2

更新:我打开了一个叫做pyth.py的脚本,然后在解释器中输入pyth_test(1,2)时就出现了错误。

谢谢你的帮助。(我为这个基础问题感到抱歉,我以前从未编程过,现在想把学习Python当作一个爱好)


import sys
sys.path.append ('/Users/clanc/Documents/Development/')
import test


printline()



## (the function printline in the test.py file
##def printline():
##   print "I am working"

5 个回答

8

在Python中,函数并不是随处都能用的(就像在PHP中那样)。你必须先声明它们。所以下面这个代码是可以正常工作的:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1, 2)

但是下面这个代码就不行:

pyth_test(1, 2)

def pyth_test (x1, x2):
    print x1 + x2
9

对我来说是有效的:

>>> def pyth_test (x1, x2):
...     print x1 + x2
...
>>> pyth_test(1,2)
3

确保你在调用这个函数之前先定义它。

56

是的,但是pyth_test的定义在哪个文件里呢?它是在被调用之前就已经定义好了吗?

编辑:

为了让你更明白,先创建一个叫test.py的文件,里面写上以下内容:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

然后运行下面的命令:

python test.py

你应该能看到你想要的输出。如果你在一个交互式的会话中,它应该是这样的:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

我希望这能解释清楚声明是怎么工作的。


为了让你了解布局是怎么回事,我们来创建几个文件。新建一个空文件夹,保持整洁,里面放:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

现在如果你运行:

python program.py

它会打印出3。现在来解释一下哪里出错了,我们把程序改成这样:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

现在看看会发生什么:

$ python program.py 
Traceback (most recent call last):
  File "program.py", line 3, in <module>
    pyth_test(1,2)
NameError: name 'pyth_test' is not defined

如上所述,Python找不到模块,原因就是上面提到的。所以你应该把声明放在最上面。

接下来,如果我们运行交互式的Python会话:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

同样的过程适用。现在,包的导入并不是那么简单,所以我建议你去了解一下Python中的模块是怎么工作的。希望这对你有帮助,祝你学习顺利!

撰写回答