1

我不知道为什么注释掉第七行时输出不同。代码如下:

#!/usr/bin/python
import threading
import time    
def loop(thread_name):      
    if False:
        print "1111"   #The print is only used to prove this code block indeed not excute 
        global dict_test   # The output will be different when commenting this line code
    else:
        dict_test = {}
    i = 0
    while i < 10:
        i+=1
        print  "thread %s %s" % (thread_name,id(dict_test))
        time.sleep(1)

t1=threading.Thread(target=loop,args=('1'))
t2=threading.Thread(target=loop,args=('2'))
t1.start()
t2.start()
t1.join()
t2.join()

如果解释是不管匹配哪个条件都预编译全局变量,为什么下面的代码会报错?

#!/usr/bin/python
import threading
import time    
def loop(thread_name):        
    if False:
        print "1111"   #The print is only used to prove this code block indeed not excute 
        global dict_test   # The output will be different when commenting or uncommenting this line code 
    else:
#        dict_test = {}
        pass
    i = 0
    while i < 10:
        i+=1
        print  "thread %s %s" % (thread_name,id(dict_test))
        time.sleep(1)

t1=threading.Thread(target=loop,args=('1'))
t2=threading.Thread(target=loop,args=('2'))
t1.start()
t2.start()
t1.join()
t2.join()
4

2 回答 2

4

要解析 Python 搜索的变量名称:

  • 本地范围

  • 任何封闭函数的范围

  • 全局范围

  • 内置插件

来源

if其他流控结构这里就不说了。因此,内部的范围if与外部的范围相同,因此现有变量dict_test成为全局变量,无论此块是否正在执行。

这可能令人惊讶,但这就是它的定义方式。

我的输出是

thread 1 50663904
thread 2 50667360
thread 1 50667360
thread 2 50667360
thread 1 50667360
thread 2 50667360
...

所以最初,当两个线程同时启动时,这两个变量是独立的。从第二次迭代开始,它们都引用同一个全局变量。

于 2013-01-18T09:13:50.277 回答
0

无论是否执行 if 语句,都适用 global 语句。所以在注释掉全局语句时,dict_test 的赋值适用于局部范围。

于 2013-01-18T09:07:25.577 回答