今天在写一个脚本时需要定义一个全局的时间变量,但是在函数中修改后一直不能更新,发现是因为函数是有自己的namespace
last_send_time = 0 def test(): last_send_time = 2 print last_send_time #will print 0 #to change it. def test(): global last_send_time last_send_time = 2 print last_send_time
From: stackoverflow
Your issue is that functions create their own namespace, which means that done
within the function is a different one than done
in the second example. Use global done
to use the first done
instead of creating a new one.
def function():
global done
for loop:
code
if not comply:
done = True
An explanation of how to use global
can be found here
时间: 2024-10-16 07:45:19