【问题标题】:How do I change nesting function's variable in the nested function如何在嵌套函数中更改嵌套函数的变量
【发布时间】:2011-09-06 02:57:04
【问题描述】:

我想在嵌套函数中定义变量以在嵌套函数中进行更改,例如

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

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

调用嵌套函数时,我希望它打印 10,但它会引发 UnboundLocalError。关键字 global 可以解决这个问题。但是由于变量 count 仅在嵌套函数的范围内使用,我希望不要将其声明为全局的。这样做的好方法是什么?

【问题讨论】:

标签: python global-variables nested-function


【解决方案1】:

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

在 Python 2.x 中,您根本无法从 nested 分配给 nesting 中的 count。但是,您可以通过不分配给变量本身,而是使用可变容器来解决它:

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

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

尽管对于不平凡的情况,通常的 Python 方法是将数据和功能包装在一个类中,而不是使用闭包。

【讨论】:

  • 你可以做的是从外部函数绑定闭包内的变量,而不是相反。考虑这种情况(当父函数作用域消失时): def a(): test = 50 def b(y): return test+ y return b 运行 a 将返回一个将 50 添加到其参数的函数。这不会修改 test,并且 test 是绑定的。如果你参数化 'a',你可以生成不同的 b - 就像高阶 lisp 函数一样。
【解决方案2】:

有点晚了,您可以像这样将属性附加到“嵌套”函数:

def nesting():

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

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

c = nesting()
print(c.count)

【讨论】:

    【解决方案3】:

    对我来说最优雅的方法:在两个 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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多