Python 如何处理对其参数具有非局部影响的内部函数?

How does Python handle inner functions with nonlocal effects on their parameters?

考虑以下函数,我们不希望它在整数 a 上保持不变,但它总是 returns (1,2):

def foo(a):
    b = 1
    c = 2
    def bar(b,c):
        b = b + a
        c = c + a
    bar(b,c)
    return (b,c)

如果我理解正确,实现 bar(b,c) 的惯用方法是完全不给它任何参数,并在其定义中声明 b 和 c 非本地。然而,我很好奇:我们如何使内部函数对其参数产生非局部影响?

使bcfunction attributes.

def foo(a):
    foo.b = 1
    foo.c = 2
    def bar():
        foo.b = foo.b + a
        foo.c = foo.c + a
    bar()
    return (foo.b,foo.c)

请注意,您不再将 b 或 c 传递给函数 bar。

this answer 中所述 Python 2.x:

Python doesn't allow you to reassign the value of a variable from an outer scope in an inner scope (unless you're using the keyword "global", which doesn't apply in this case).

这将 return (2,3):

def foo(a):
    b = 1
    c = 2
    def bar(b,c):
        b = b + a
        c = c + a
        return b, c
    b, c = bar(b,c)
    return (b,c)

print(foo(1))

函数参数是总是局部变量。但是,您可以传入可变对象,并将您的操作应用于间接引用的值:

def foo(a):
    b = [1]
    c = [2]
    def bar(b, c):
        b[0] += a
        c[0] += a
    bar(b, c)
    return (b[0], c[0])

您对可变对象所做的更改将与对这些对象的任何其他引用共享,包括 foo() 中的局部变量。

但是,如果你想让某个东西成为一个闭包,就让它成为一个闭包。没有 nonlocal 值和 return.

无法处理的用例