python的namespace问题 - webdancer's Blog

python的namespace问题

webdancer posted @ 2013年4月06日 04:57 in 编程语言 with tags python , 3336 阅读

1.问题

写程序的时候,出现了一个bug,看了很久也没有发现问题。程序的逻辑模样大致如下所示:

for i in range(4):
    x = [ e**i for i, e in enumerate(range(5))] 
    y = 2 * i
    print y

如果对python很熟悉的,一眼就可以看出问题的所在。程序的原意是:y = 2 * i 这条语句中i与第一行中的i一致的,但是却使用了第二行中的i值,但是程序依然循环了四次。打印的结果是:

8
8
8
8 

这令人非常的疑惑,主要是在python 2,x中,list comprehension中的变量的scope没有仅限于‘[ ]’中,而是漏了出来。这的确有点不太符合逻辑,因为在理解上,‘[ ]’中的变量的scope仅限于里面,更加符合直观的感觉。

2.解决

解决的方法:

  1. 避免名字冲突就行了,比如把第二行的i换成j。
  2. 升级python的版本。在python 3.x中,这个问题就不存在了,list comprehension表达式有了自己的scope.(是不是应该升级到python 3了??但是好像一些包还是支持3.x不太好呀,囧。。。)

3.python 的namespace和scope

namespace就是一个从名字到对象的映射,现在的python好像就是用字典数据结构实现的。对于namespace注意的就是生命周期(lifetime)和作用域(scope)。所谓生命周期就是实现namespace的对象在内存中存在的时间,而作用域(scope)就是namespace在程序中起作用的文本区域。

Avatar_small
依云 说:
2013年4月06日 18:49

咦?我才知道 Python 3 的 list comprehension 有自己的作用域了耶~

Avatar_small
webdancer 说:
2013年4月07日 04:14

就是还没下决心升级到py3呀。。。

PSEB 11th Question P 说:
2022年8月24日 02:48

The Punjab Board Class 11th Important Model Question Paper 2023 would be helpful to those who desire to succeed in the Class 11 Punjab Board Exam. Due to a more precise indication of the assignments and tests they will be expected to complete during the academic year, students will be better equipped to handle the Punjab Board 11th Grade. PSEB 11th Question Paper 2023 It will be important for students to participate in its creation, and a well-designed Subjects Wise Important Model Question Paper 2023 will work to make it as interactive as possible by including students in the process of making it.

seo service UK 说:
2023年10月31日 23:12

hello, your website is really good. We do appreciate your give good results


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee