Python导入更新参考

时间:2017-12-04 22:09:51

标签: python

我想将一个refence导入一个对象,在导入引用的初始文件已被python解析之后更新其值。例如:

runner.py

from store import modify_var
from importer import a_function

print('>>runner')
modify_var()
a_function()

store.py

my_var = None

def modify_var():
    global my_var
    my_obj = MyObj()
    my_var = my_obj
    print('>>store, my_var has been set to: {0}'.format(my_var))

class MyObj(object):
    x = 2

importer.py

from store import my_var

print('>>importer, my_var outside function (before has been set): {0}'.format(my_var))

def a_function():
   print('>>importer, my_var after is has been set: {0}'.format(my_var))
运行runner.py

控制台输出

>>importer, my_var outside function (before has been set): None
>>runner
>>store, my_var has been set to: <tests.store.MyObj object at 0x7fbfc683a1d0>
>>importer, my_var after is has been set: None

我试图找出如何导入my_var,这样当我在函数中调用它时,它的值不是None。

1 个答案:

答案 0 :(得分:0)

我认为它不喜欢你在store.py中给它一个值后声明my_var的事实。请尝试以下方法之一:

在store.py中,创建另一个将my_var返回为none的方法:

def my_var_none():
    my_var = None
    return my_var

然后,保持runner.py不变,并在importer.py:

from store.py import my_var_none()