当我使用从pprocess调用的函数时,似乎无法修改Python中的全局变量。以下是我的示例:
import pprocess
import time
numbers=[0,0,0,0,0,0,0,0,0,0]
# find system time and store in global variable
def find_time(index):
global numbers
x=time.time()
print "Setting element %s of numbers to %f" % (index, x)
numbers[index]=x
return x
# parallel execution of the function
results=pprocess.pmap(find_time, [0,1,2,3,4,5,6,7,8,9], limit=6)
for y in results:
print '%f' % y
# this list is unchanged
print numbers
# serial execution of the function
for x in [0,1,2,3,4,5,6,7,8,9]:
find_time(x)
# now it seems to work
print numbers
“numbers”只是一个零的列表,为了演示,我试图将每个列表元素设置为当前系统时间。当使用pprocess调用时,这不起作用,但当我使用简单的for循环调用函数时,全局变量就会改变。
我花了一些时间阅读关于全局变量的内容,并真诚地希望这不是一个琐碎的问题。有人能向我解释一下发生了什么吗?
非常感谢,
Enno
global
关键字。即使你没有将其定义为全局变量,Python也可以轻松地改变全局对象。只有在通过赋值更改变量引用的对象时才需要使用global
关键字。 - mgilson