18

我是 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"
4

1 回答 1

28

您需要声明它weight是 global inside GetLiveWeight,而不是它之外。

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

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

于 2013-07-28T19:10:22.750 回答