Python nonlocal语句做了什么(在Python 3.0及更高版本中)?
官方Python网站上没有文档,help("nonlocal")也没有用.
我正在尝试在Python 2.6中实现一个闭包,我需要访问一个非局部变量,但似乎这个关键字在python 2.x中不可用.如何在这些版本的python中访问闭包中的非局部变量?
在下面的Python代码中,我得到了一个UnboundLocalError.据我所知,局部函数共享包含函数的局部变量,但这似乎不是这里的情况.我认识到a在这种情况下这是一个不可变的值,但这应该不是问题.
def outer():
a = 0
def inner():
a += 1
inner()
outer()
Run Code Online (Sandbox Code Playgroud)
看起来内部函数已经收到了父函数中所有引用的副本,因为UnboundLocalError如果值的值a被包装在一个可变类型中,我就不会得到异常.
有人能够澄清这里的行为,并指出相应的Python文档吗?
我想获取带有指定“日志”标签的主题:
在嵌套函数中get_topics_with_log_tag,我设置了变量topics_with_log_tagnonlocal:
def log(request):
"""Show all topics and entries with log tags"""
topics = Topic.objects.all()
#select entries with log tag
def get_topics_with_log_tag(topics):
nonlocal topics_with_log_tag
topics_with_log_tag = []
for topic in topics:
for entry in topic.entry_set.all():
if "#log" in entry.tags:
topics_with_log_tag.append(topic)
get_topics_with_log_tag(topics)
Run Code Online (Sandbox Code Playgroud)
它抛出语法错误:
SyntaxError: no binding for nonlocal 'topics_with_log_tag' found
Run Code Online (Sandbox Code Playgroud)
实际上,我确实绑定了它 topics_with_log_tag = []
上面的代码可以用冗余的方式重写为
topics = Topic.objects.all()
#select entries with log tag
def get_topics_with_log_tag(topics):
# nonlocal topics_with_log_tag
topics_with_log_tag = []
for topic in topics:
for entry …Run Code Online (Sandbox Code Playgroud)