在Python中用线程修改全局变量

1 投票
1 回答
4583 浏览
提问于 2025-04-18 14:22

我正在尝试写一个脚本,每10秒更新一次一个全局变量。为了简单起见,我们就让这个变量q每次加1。

import time, threading

q = 0
def f(q):
    # get asset position every 10 seconds:
    q += 1
    print q

    # call f() again in 10 seconds
    threading.Timer(10, f).start()


# start calling f now and every 10 sec thereafter
f(q)

但是,Python却给我报错:

UnboundLocalError: local variable 'q' referenced before assignment

那么,正确的方法来改变变量q是什么呢?


这个例子使用了线程,但没有更新任何值。每n秒运行特定代码

1 个回答

4

你需要明确地把 q 声明为全局变量。否则,q += 1 会让解释器感到困惑。

import threading

q = 0
def f():
    global q
    q += 1
    print q
    threading.Timer(10, f).start()

f()

撰写回答