从另一个模块导入变量会导致AttributeError

时间:2014-10-09 22:03:38

标签: python python-2.7

当我尝试打印var1的值时,我得到AttributeError: 'function' object has no attribute 'var1'我已经研究了几个小时,一些答案提到了创建类,我想可能有一个更简单的解决方案:< / p>

这是主要的脚本

#script.py
from module1 import function1
from module2 import function2

function1(arg) #It calls the function and works fine

print function1.var1 #HERE IT BREAKS WITH THE AttributeError!

function2(otherArgs) #I suppose this will also break...

这是第一个模块

#module1.py
def function1(args1):
    #some stuff
    var1 = 'some'

这里第二个也调用了var1

#module2.py
import module1
def function2(args2):
    #some stuff
    print module1.var1

1 个答案:

答案 0 :(得分:1)

函数就像黑盒一样,因此函数内的所有变量仅用于计算最终结果。函数完成后,它会返回您告诉它的任何结果,然后删除所有局部变量。我认为你要做的事情应该更像是这样:

#module1.py
def function1(args1):
    #some stuff
    var1 = 'some'
    return var1

#script.py
from module1 import function1
from module2 import function2

var1 = function1(arg) #It calls the function and works fine

print var1

function2(otherArgs)

属性仅适用于类,一个函数在运行后不会保留任何内容,除非您告诉它返回的内容以及在执行函数期间修改的任何全局变量。