这是一组Python的短脚本。但是,我遇到了更新全局变量的问题。
# A.py
data = [[]] # global data
def work1(list):
data.append(list)
def work3():
print (data)
# B.py
from A import work1
def work2():
for each in input:
work1(each) # call work1
# C.py
from A import work3
def work4():
work3() # call work3
“数据”是列出长句的列表。 没有“work2”,“work4”就不会被调用。
但是,在“work3”中,“数据”始终为空,未更新,为“[[]]” 我怎样才能解决这个问题? (python的版本是3.4.4)
答案 0 :(得分:0)
为所有全局值创建单独的文件
#globals.py
class MyGlobals(object):
data = [[]] # global data
#c.py
from globals import MyGlobals
def work1(list):
MyGlobals.data.append(list)
def work3():
print (MyGlobals.data)
#b.py
from globals import MyGlobals
import c
input = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
def work2():
for each in input:
C.work1(each) # call work1
#a.py
from globals import MyGlobals
import c
def work4():
c.work3() # call work3
if __name__ == "__main__":
work4();
sh-4.3$ python a.py
[[]]
sh-4.3$
如果您现在想要更新全局值,可以在文件b.py里面调用work2()函数
#a.py
from globals import MyGlobals
import c
import b
def work4():
c.work3() # call work3
if __name__ == "__main__":
b.work2()
work4()
sh-4.3$ python a.py
[[], [1, 3, 4], [2, 4, 4], [3, 4, 5]]
输出中有一个空列表,因为我不确定如何存储它们,因为在全局数据中存在一个现有的空列表,即data = [[]]
使其按照您的要求运作。将您的全局
list
放入一个文件中,并将该文件导入您将使用它的每个其他模块/文件中。
#a.py
data = [[]] # global data
#b.py
import a
def work1(list):
a.data.append(list)
def work3():
print (a.data)
#c.py
import a
import b
input = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
def work2():
for each in input:
b.work1(each) # call work1
#main.py
import a
import b
import c
def work4():
b.work3() # call work3
if __name__ == "__main__":
c.work2()
work4()
sh-4.3$ python main.py
[[], [1, 3, 4], [2, 4, 4], [3, 4, 5]]
sh-4.3$