Python 修改global 变量

今天在写一个脚本时需要定义一个全局的时间变量,但是在函数中修改后一直不能更新,发现是因为函数是有自己的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

posted @ 2015-09-15 11:14  _Doraemon  阅读(720)  评论(0编辑  收藏  举报