##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = Py变量域细辨 = ##startInc == 应该是什么? == {{{ Iceberg reply-to python-cn@googlegroups.com to python-cn`CPyUG`华蟒用户组 date Fri, Dec 19, 2008 at 16:38 subject [CPyUG:74106] 变量作用域的有趣问题 }}} 首先,请看一下这个短程序,并预测它的运行结果。 {{{#!python value=0 aList=[value for value in (1,2)] print value }}} 程序到此为止。如果你想挑战一下自己的水平,就在此暂停,先考虑出结果,再继续往下看 === 汗颜ing,,, === {{{ > >> 如果你预测的结果是零,恭喜,你和我一样,答错了!那么,这个贴子就是你我一起深刻反省的机会。 > > > 应该是2啊,为什么你会认为[]会有自己的作用域呢? }}} 见:: http://docs.python.org/reference/executionmodel.html {{{ Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. }}} * name是放在最内层的block里,block只能是a module, a function body, and a class definition.所以,很清楚,[]不是block,不会有自己的scope。 这位同学的一句"为什么你会认为[]会有自己的作用域呢"问得我实在是汗颜。还好据其他一些反馈,说Python3.0里,这个程序的输出确实是0,于是我可以无耻地说,"这个问题请拿去问Python3.0的开发团队吧"。 *^_^* * 言归正传。我本以为,[],或者更准确地说,list comprehension,应该有自己的作用域。因为,既然写`list comprehension`时不要求事先定义循环变量,那么这个循环变量就应该是一个被自动初始化的局部变量,最后也就应该被自动删除。否则的话就是一种"副作用",而且这种副作用应该不是语言设计者的本意。当然,现在事实证明在Python2.x中确实存在这种副作用,那么我们除了知道它、适应它,也没有其它的办法。这也是我写这个贴子的目的。呵呵,不出所料成为了一个很火的贴子,应该达到我的目的了。 * 顺便发散回忆一下,我依稀记得C++里面,花括号{}内部就是一个作用域。另外,for (int i=0;i<100;i++) {...} 执行完 之后,不记得变量i是否也不存在了。不好意思,没有自行求证这两个问题。因为手头没有C++环境。毕竟也快两年没写过一行C++代码了 `花括号是一个作用域,for 的循环变量也只限于 for 循环之内,不过 vc6 不符合这个规范,我知道的就这么多。` ~ Jay True == 比照运行 == {{{ Jiahua Huang reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Fri, Dec 19, 2008 at 20:29 subject [CPyUG:74146] Re: 变量作用域的有趣问题 }}} `python 2.4, 2.5, 2.6, 3.0 下的运行` {{{ $ python2.4 Python 2.4.5 (#2, Jul 31 2008, 18:51:48) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> value=0 >>> aList=[value for value in (1,2)] >>> value 2 $ python Python 2.5.2 (r252:60911, May 7 2008, 15:19:09) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> value=0 >>> aList=[value for value in (1,2)] >>> value 2 $ python2.6 Python 2.6 (r26:66714, Oct 21 2008, 21:50:32) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> value=0 >>> aList=[value for value in (1,2)] >>> value 2 $ python3.0 Python 3.0b3 (r30b3:65927, Sep 14 2008, 01:05:23) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> value=0 >>> aList=[value for value in (1,2)] >>> value 0 }}} ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]