V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
bearzx
V2EX  ›  Python

Python递归时函数内变量无法引用的问题

  •  
  •   bearzx · 2013-10-27 22:49:00 +08:00 · 3784 次点击
    这是一个创建于 3827 天前的主题,其中的信息可能已经有所发展或是发生改变。
    hi各位好,
    我今天写code的时候遇到一个问题,考虑以下代码:

    def a():
    def b():
    if a != 0:
    print a
    a -= 1
    b()
    a = 100
    b()

    a()

    运行的话就会报出a变量没有创建的错误。但是这样是不是说这种情况下在递归的内部函数里就不能去引用外部函数的变量了?那如果有这种需求的话就只能定义全局变量了么。。。

    求大神们指导
    10 条回复    1970-01-01 08:00:00 +08:00
    bearzx
        1
    bearzx  
    OP
       2013-10-27 22:49:52 +08:00
    我擦这缩进。。。
    bearzx
        2
    bearzx  
    OP
       2013-10-27 23:25:34 +08:00
    貌似可以用python3的nonlocal解决。。。
    mengzhuo
        3
    mengzhuo  
       2013-10-27 23:27:29 +08:00   ❤️ 1
    能用gist不……

    Python的变量规则好像是是Local Closure Global Buildin

    可以看看这个
    http://stackoverflow.com/questions/4851463/python-closure-write-to-variable-in-parent-scope
    bearzx
        4
    bearzx  
    OP
       2013-10-28 00:15:48 +08:00
    @bearzx v2ex可以用gist?
    bearzx
        5
    bearzx  
    OP
       2013-10-28 00:25:31 +08:00
    @mengzhuo 很有帮助,谢谢~
    est
        6
    est  
       2013-10-28 09:08:46 +08:00
    a 又是变量又是函数?
    bearzx
        7
    bearzx  
    OP
       2013-10-28 09:22:40 +08:00
    @est 没。。是我写的不清楚,可以把a函数里面的a是另一个东西
    VYSE
        8
    VYSE  
       2013-10-28 10:11:44 +08:00 via Android
    把变量放在tuple或list里传
    bearzx
        9
    bearzx  
    OP
       2013-10-28 10:30:05 +08:00
    @VYSE 嗯mengzhuo给的链接里用的是这么个方法,不过python3里面有一个nonlocal关键字也可以实现这个需求
    roricon
        10
    roricon  
       2013-10-29 14:44:41 +08:00
    为什么我先想到的是构造一个generator然后重构它的__sub__方法来实现……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1843 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:24 · PVG 00:24 · LAX 09:24 · JFK 12:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.