【问题标题】:Python Global Variable not updatingPython全局变量不更新
【发布时间】:2013-07-28 19:09:37
【问题描述】:

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

【问题讨论】:

    标签: python global-variables


    【解决方案1】:

    您需要声明weight 是全局的内部 GetLiveWeight,而不是外部。

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

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

    【讨论】:

    • 谢谢我已经尝试过了,但我似乎仍然无法获得更改权重变量的功能,它似乎总是保持设置为值?
    • 你确定条件interupt == False(通常写成not interupt)是真的吗?换句话说,您确定while-loop 中的代码正在执行吗?
    • 是的,我在 while 循环中添加了一个 print 来输出变量权重,它工作正常。它可能与我称之为'try: threading.Thread(target = GetLiveWeight).start() print liveWeight except: print "Error: unable to start thread"'的方式有关。
    • try-suite 中的 print 语句在 其他线程修改 weight 之前被执行。
    猜你喜欢
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2020-05-23
    • 2020-08-25
    相关资源
    最近更新 更多