Python:从导入的文件调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19056240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: calling function from imported file
提问by RageCage
How do you call a function from an imported file? for example:
如何从导入的文件中调用函数?例如:
Test:
测试:
import test2
def aFunction():
print "hi there"
Test2:
测试2:
import test
aFunction()
This give me a name error, saying my function isn't defined. I've also tried:
这给了我一个名称错误,说我的函数没有定义。我也试过:
from test import aFunction
And:
和:
from test import *
I've also tried not importing test2 in test. I'm coming to Python from C++, so I fear I'm missing something blatantly obvious to veteran Python progammers...
我也试过不在测试中导入 test2。我是从 C++ 开始学习 Python 的,所以我担心我错过了一些对资深 Python 程序员来说显而易见的东西......
采纳答案by Martijn Pieters
You are creating a circular import. test.py
imports test2.py
which tries to import test.py
.
您正在创建循环导入。test.py
进口test2.py
这些尝试导入test.py
。
Don't do this. By the time test2
imports test
, that module has not completed executing all the code; the function is not yet defined:
不要这样做。到test2
import 时test
,该模块还没有完成所有代码的执行;该函数尚未定义:
test
is compiled and executed, and an empty module object is added tosys.modules
.The line
import test2
is run.test2
is compiled and executed, and an empty module object is added tosys.modules
.The line
import test
is run.test
is already present as a module insys.modules
, this object is returned and bound to the nametest
.
A next line tries to run
test.aFunction()
. No such name exists intest
. An exception is raised.
The lines defining
def aFunction()
are never executed, because an exception was raised.
test
被编译和执行,并且一个空的模块对象被添加到sys.modules
.线路
import test2
运行。test2
被编译和执行,并且一个空的模块对象被添加到sys.modules
.线路
import test
运行。test
已作为模块存在sys.modules
,则返回此对象并绑定到名称test
。
下一行尝试运行
test.aFunction()
。中不存在这样的名称test
。引发异常。
定义的行
def aFunction()
永远不会执行,因为引发了异常。
Remove the import test2
line, and run test2.py
directly, and importing the function will work fine:
去掉那import test2
行,test2.py
直接运行,导入函数就可以了:
import test
test.aFunction()