请考虑以下代码:
from threading import Thread
def main():
number = 5
class my_thread(Thread):
def __init__(self, range):
Thread.__init__(self)
self.range = range
def run(self):
global number
for i in self.range:
number += 1
t1 = my_thread(range(4))
t1.start()
t1.join()
print number
main()
此程序的输出是
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Tools\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Dev\Workspace\Hello World\Hello.py", line 14, in run
number += 1
NameError: global name 'number' is not defined
5
显然,my_thread
无法访问number
。为什么这样,我怎样才能正确访问它?
答案 0 :(得分:2)
你需要让number
成为第一个定义的全局,如下所示:
def main():
global number
number = 5
...etc...