为什么子函数不继承 Python 中的作用域? [英] Why doesn't a sub-function inherit scope in Python?
问题描述
我不明白为什么以下方法不起作用:
def foo( x ):n = 1总和 = 0定义栏():n -= 1对于范围内的 i (0,10):y = x+i+nx += i总和 += y打印 "{0} = {1} + {2} + {3}".format(y,x,i,n)酒吧()打印 "summe =", summe返回夏天
为什么bar()
没有继承foo()
的作用域?这是我需要忘记的 C'ism 吗?有没有办法让我做到这一点?
PEP 3104 为这个问题提供了解释和解决方案.问题是 Python 将任何对名称的赋值视为 local 变量声明.
<预><代码>>>>n = 1>>>定义栏():>>>n = n + 1>>>>>>酒吧()回溯(最近一次调用最后一次):文件<pyshell#8>",第 1 行,在 <module> 中酒吧()文件<pyshell#7>",第 2 行,在栏中n = n + 1UnboundLocalError:赋值前引用了局部变量n"如果您使用没有 nonlocal 关键字的 Python 版本,有一些解决方法可以解决此问题.一个丑陋的技巧是将您的变量包装在一个列表中:
<预><代码>>>>n=[1]>>>定义栏():>>>n[0] = n[0] + 1>>>>>>酒吧()>>>n[2]虽然这个技巧有效,但通常最好重写代码以消除对非本地赋值的需要.
I don't understand why the following doesn't work:
def foo( x ):
n = 1
summe = 0
def bar():
n -= 1
for i in range(0,10):
y = x+i+n
x += i
summe += y
print "{0} = {1} + {2} + {3}".format(y,x,i,n)
bar()
print "summe =", summe
return summe
Why is it that bar()
doesn't inherit the scope of foo()
? Is this a C'ism that I need to forget? Is there a way I can make that work?
PEP 3104 provides an explanation and a solution for this problem. The issue is Python treats any assignment to a name as a local variable declaration.
>>> n = 1
>>> def bar():
>>> n = n + 1
>>>
>>> bar()
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
bar()
File "<pyshell#7>", line 2, in bar
n = n + 1
UnboundLocalError: local variable 'n' referenced before assignment
There is a few workarounds for this problem if you use a Python version without the nonlocal keyword. One ugly trick is to wrap your variable in a list:
>>> n=[1]
>>> def bar():
>>> n[0] = n[0] + 1
>>>
>>> bar()
>>> n
[2]
Although this trick works, it is usually better to rewrite the code to remove the need for non-local assignments.
这篇关于为什么子函数不继承 Python 中的作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!