python:如何捕获在非全局祖先外部作用域中声明的变量? [英] python: How do I capture a variable declared in a non global ancestral outer scope?

查看:42
本文介绍了python:如何捕获在非全局祖先外部作用域中声明的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定:

def f():
    x = 0
    def g():
        h()
    def h():
        x += 1
        print(x)
    g()

>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in f
  File "<stdin>", line 4, in g
  File "<stdin>", line 6, in h
UnboundLocalError: local variable 'x' referenced before assignment
>>>

如何让 h 看到 x 变量?

How can I make h see the x variable?

谢谢.

编辑

应该早点提到的,我使用的是 Python 2.7.3

Should have mentioned it earlier, I am using Python 2.7.3

推荐答案

您可以使 x 成为 函数属性:

def f():
    f.x = 0
    def g():
        h()
    def h():
        f.x += 1
        print(f.x)
    g()

此外,从 Python 3 开始,您可以使用 nonlocal 关键字.

Also, as of Python 3, you can use nonlocal keyword.

这篇关于python:如何捕获在非全局祖先外部作用域中声明的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆