是的,但是在哪个文件中pyth_test
的定义声明于?它也是在调用之前定位的吗?
Edit:
为了正确理解它,创建一个名为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
程序.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 一起使用 http://docs.python.org/tutorial/modules.html。我希望这对您有所帮助,并祝您学习顺利!