注意:我已经减少了我的问题,因此代码只有几行(相比于600行)
我有一个问题:我想从main.py
导入文件slave.py
。 slave.py
引用了main.py
中的一个函数,当然我得到了NameError: name 'funcFromMain' is not defined
这是我的main.py代码:
import slave
def funcFromMain():
return 6
print(slave.funcFromSlave())
这是我的slave.py代码:
def funcFromSlave():
one = funcFromMain() # <- this doesn't work
two = 2
return (one + two)
我得到了确切的错误:(请注意,两个文件都在完全相同的目录中)
Traceback (most recent call last):
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 6, in <module>
print(slave.funcFromSlave())
File "C:\Users\PrinceOfCreation\Documents\test\slave.py", line 2, in funcFromSlave
one = funcFromMain()
NameError: name 'funcFromMain' is not defined
我尝试在slave.py的顶部添加import main
,并收到以下错误:
Traceback (most recent call last):
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 1, in <module>
import slave
File "C:\Users\PrinceOfCreation\Documents\test\slave.py", line 1, in <module>
import main
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 6, in <module>
print(slave.funcFromSlave())
AttributeError: module 'slave' has no attribute 'funcFromSlave'
使用from slave import funcFromSlave
代替main:
Traceback (most recent call last):
File "C:\Users\PrinceOfCreation\Documents\test\main.py", line 6, in <module>
print(funcFromSlave())
File "C:\Users\PrinceOfCreation\Documents\test\slave.py", line 2, in funcFromSlave
one = funcFromMain()
NameError: name 'funcFromMain' is not defined
答案 0 :(得分:1)
首先,您不能像这样导入python模块:
import slave.py
必须是
from slave import funcFromSlave # to get the funcFromSlave function from slave script
并且您需要确保slave.py
在main.py
的同一目录中,或者
您需要精确调整slave.py所在的子目录
对于以后的错误,最好避免循环导入,否则会产生问题,最好的做法是将funcFromMain()
的值发送到funcFromSlave
main.py:
from slave import funcFromSlave
def funcFromMain():
return 6
print(funcFromSlave(funcFromMain()))
slave.py:
def funcFromSlave(funcFromMain):
one = funcFromMain
two = 2
return (one + two)
运行main.py时的输出:
8