一尘不染

Python全局变量未更新

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"

阅读 164

收藏
2020-12-20

共1个答案

一尘不染

需要声明的是weight是全球性的 内部 GetLiveWeight,而不是外面。

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

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

2020-12-20