Python全局变量不更新

时间:2013-07-28 19:09:37

标签: python

我是Python和编程的新手,但似乎无法理解为什么这个函数不会更新全局变量

global weight
weight = 'value'
def GetLiveWeight():
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

我也试过这个

weight = 'value'
def GetLiveWeight():
    global weight
    SetPort()
    while interupt == False:
        port.write(requestChar2)
        liveRaw = port.read(9)
        liveRaw += port.read(port.inWaiting())
        time.sleep(0.2)
        weight = liveRaw.translate(None, string.letters)
    return weight

try:
    threading.Thread(target = GetLiveWeight).start()
    print liveWeight
except:
    print "Error: unable to start thread"

1 个答案:

答案 0 :(得分:18)

您需要声明weightGetLiveWeight内的全局,而不是在其外部。

weight = 'value'
def GetLiveWeight():
    global weight

global statement告诉Python,在GetLiveWeight函数的范围内,weight引用全局变量weight,而不是一些新的局部变量weight