2011-06-01 157 views
16

我想在嵌套函数定义的嵌套函数被改变的变量,像如何更改嵌套函数的变量在嵌套函数

def nesting(): 
    count = 0 
    def nested(): 
     count += 1 

    for i in range(10): 
     nested() 
    print count 

当嵌套调用函数时,我希望打印10,但会引发UnboundLocalError。全球关键词可以解决这个问题。但由于变量计数只用于嵌套函数的范围,因此我不希望将其声明为全局函数。有什么好办法做到这一点?

+1

可能重复(http://stackoverflow.com/questions/7935966/python-overwriting-variables-in-nested-functions) – ikdc 2014-05-15 21:30:51

回答

21

在Python 3.x中,你可以使用nonlocal声明(在nested)来告诉Python你的意思是分配给count变量nesting

在Python 2.x中,您根本无法从nested分配到中的count。但是,您可以工作围绕它通过不分配给变量本身,而是利用一个可变容器:

def nesting(): 
    count = [0] 
    def nested(): 
     count[0] += 1 

    for i in range(10): 
     nested() 
    print count[0] 

虽然不平凡的情况下,普通的Python的办法是包裹在数据和功能类,而不是使用闭包。

+0

你可以做的是从外部函数中绑定闭包内的变量,但不是相反。考虑这种情况下(当父温控功能范围已经消失): DEF一个(): 测试= 50 DEF B(y)的: 返回测试+ Y 返回b 运行将返回的功能,增加了50到它的参数。这不会修改测试,并且测试是受约束的。如果你参数化了'a',你可以生成不同的b - 而不是更高阶的lisp函数。 – 2011-06-01 09:22:45

+1

Py3K提示+1 – gecco 2013-03-07 15:46:02

4

有点晚,你可以将一个属性设置为“嵌套”功能,像这样:

def nesting(): 

    def nested(): 
     nested.count += 1 
    nested.count = 0 

    for i in range(10): 
     nested() 
    return nested 

c = nesting() 
print(c.count) 
0

对我来说,最简洁的方法:在两个版本的Python工程100%。

def ex8(): 
    ex8.var = 'foo' 
    def inner(): 
     ex8.var = 'bar' 
     print 'inside inner, ex8.var is ', ex8.var 
    inner() 
    print 'inside outer function, ex8.var is ', ex8.var 
ex8() 

inside inner, ex8.var is bar 
inside outer function, ex8.var is bar 

更多:http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/

[在嵌套函数的Python覆盖变量]的