Python 如何在其他文件中移动函数
这是Python 如何在其他文件中移动函数,python,Python,这是myfunction.py def a(): print 'function a' b() def c(): print 'function c' from otherfunction import b a() 这是otherfunction.py def b(): print 'function b' c() 预期产量为 function a function b function c 相反,我得到了 function a function b Trace
myfunction.py
def a():
print 'function a'
b()
def c():
print 'function c'
from otherfunction import b
a()
这是otherfunction.py
def b():
print 'function b'
c()
预期产量为
function a
function b
function c
相反,我得到了
function a
function b
Traceback (most recent call last):
File "/path/myfunction.py", line 10, in <module>
a()
File "/path/myfunction.py", line 3, in a
b()
File "/path/otherfunction.py", line 3, in b
c()
NameError: global name 'c' is not defined
我得到这个输出:
Traceback (most recent call last):
File "/path/myfunction.py", line 8, in <module>
from otherfunction import b
File "/path/otherfunction.py", line 1, in <module>
from myfunction import c
File "/path/myfunction.py", line 8, in <module>
from otherfunction import b
ImportError: cannot import name b
这是输出
function a
function a
function b
function c
function b
function c
它运行时没有错误,但显然函数被多次调用?我真的不明白为什么会这样。即使没有错误,也不是我想要的
from myfunction import c
在otherfunction.py中
这将确保otherfunction.py
中的代码可以看到c
函数,就像您在myfunction.py
中从otherfunction导入b一样
另外,Python将处理循环依赖关系,所以您不必担心这一点。您没有在otherfunction中导入c(),所以它不知道它。尝试:
from myfunction import c
def b():
print 'function b'
c()
但一般来说,创建这样的循环引用是一个糟糕的主意,最好将c()函数移到另一个文件中更改“otherfunction.py”,如下所示:
def b():
from myfunction import c
print 'function b'
c()
已经尝试过了,它不起作用:我得到了
导入错误:无法导入名称b
无法导入名称b
意味着你正在从myfunction导入b执行,而不是从myfunction导入c
执行。我编辑了我的帖子,它运行时没有错误,但不会产生预期的输出
from myfunction import c
def b():
print 'function b'
c()
def b():
from myfunction import c
print 'function b'
c()