导入其他文件并使用main中的功能

时间:2019-04-07 16:33:50

标签: python function import

注意:我已经减少了我的问题,因此代码只有几行(相比于600行)

我有一个问题:我想从main.py导入文件slave.pyslave.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

1 个答案:

答案 0 :(得分:1)

首先,您不能像这样导入python模块:

import slave.py

必须是

from slave import funcFromSlave # to get the funcFromSlave function from slave script

并且您需要确保slave.pymain.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