推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wenLiangcan
V2EX  ›  Python

用 closure 实现的叠加器(counter)出错,求解释原因

  •  
  •   wenLiangcan · Apr 8, 2014 · 3381 views
    This topic created in 4430 days ago, the information mentioned may be changed or developed.
    (似乎没法分开显示不同的文件。。。)

    看了这篇文章(http://coolshell.cn/articles/10739.html),有一个 Lua 写的 counter,觉得有趣:
    https://gist.github.com/wenLiangcan/10135400#file-counter-lua

    于是学着用 Python 写了一下,可是出错了:
    https://gist.github.com/wenLiangcan/10135400#file-er_counter-py

    搜索后看到这篇文章(http://jjinux.blogspot.com/2006/10/python-modifying-counter-in-closure.html),说把记录计数的变量换做列表就可以了:
    https://gist.github.com/wenLiangcan/10135400#file-counter-py

    请问这是为什么呢?上面文章提到的“to box variables within a closure”又是什么意思?



    谢谢
    7 replies    1970-01-01 08:00:00 +08:00
    monsterxx03
        1
    monsterxx03  
       Apr 8, 2014   ❤️ 2
    python闭包的经典问题

    i+=1 等价于i = i + 1, 语句从左向右执行,先是`i=`, 注意这里就覆盖了外部的i,实际上外部的i已经不可见了,然后`i+1`, 但此时外部的i在当前作用域中已经不可见,内部的i还未创建完成,等号右边的还没执行完成呢。。。所以会找不到这个i。

    lua能过,应该是语法解释器内部的逻辑和python不一样吧。
    wenLiangcan
        2
    wenLiangcan  
    OP
       Apr 8, 2014
    @monsterxx03 那为什么列表又不会被覆盖呢?
    monsterxx03
        3
    monsterxx03  
       Apr 9, 2014
    因为 i= xxx是在定义变量, i[0] =xxx 不是定义,只是赋值操作。
    wenLiangcan
        4
    wenLiangcan  
    OP
       Apr 9, 2014 via Android
    @monsterxx03 原来如此!
    josephok
        5
    josephok  
       Apr 12, 2014
    试试:
    <script src="https://gist.github.com/josephok/10524138.js"></script>
    josephok
        6
    josephok  
       Apr 12, 2014   ❤️ 1
    wenLiangcan
        7
    wenLiangcan  
    OP
       Apr 15, 2014
    @josephok 原来还有 nonlocal 这个关键字,学习了,v2ex 竟然没有提醒,现在才看到。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5685 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 06:10 · PVG 14:10 · LAX 23:10 · JFK 02:10
    ♥ Do have faith in what you're doing.