非本地关键字在Python 2.x [英] nonlocal keyword in Python 2.x

查看:108
本文介绍了非本地关键字在Python 2.x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Python 2.6中实现一个闭包,我需要访问一个非本地变量,但似乎这个关键字在python 2.x中不可用。如何在这些版本的python中的闭包中访问非本地变量?

I'm trying to implement a closure in Python 2.6 and I need to access a nonlocal variable but it seems like this keyword is not available in python 2.x. How should one access nonlocal variables in closures in these versions of python?

推荐答案

Python可以 2.x中的变量,只是不更改 。这是恼人,但你可以解决它。

Python can read nonlocal variables in 2.x, just not change them. This is annoying, but you can work around it. Just declare a dictionary, and store your variables as elements therein.

要使用维基百科中的示例:

To use the example from Wikipedia:

def outer():
    d = {'y' : 0}
    def inner():
        d['y'] += 1
        return d['y']
    return inner

f = outer()
print(f(), f(), f()) #prints 1 2 3

这篇关于非本地关键字在Python 2.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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