从另一个模块导入变量将导致AttributeE

2024-04-20 10:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是主剧本

#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

Tags: frompyimportobjectdeffunctionsomemodule1
1条回答
网友
1楼 · 发布于 2024-04-20 10:19:29

函数的行为类似于黑匣子,因此函数中的所有变量仅用于最终结果的计算。一旦函数完成,它将返回您告诉它的任何结果,然后删除所有局部变量。我认为你要做的应该是这样的:

#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)

属性只适用于类,函数运行后不保留任何内容,只保留您告诉它返回的内容和在函数执行期间修改的任何全局变量。你知道吗

相关问题 更多 >