Python全局变量未更新 [英] Python Global Variable not updating

查看:75
本文介绍了Python全局变量未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im new with Python and programming but cant seem to understand why this function does not update the global variable

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"

推荐答案

你需要声明 weight 是全局的 inside GetLiveWeight,而不是外面.

You need to declare that weight is global inside GetLiveWeight, not outside it.

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

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

The global statement tells Python that within the scope of the GetLiveWeight function, weight refers to the global variable weight, not some new local variable weight.

这篇关于Python全局变量未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆