Python如何使用非局部效应处理内部函数?

考虑以下函数,我们希望在整数a上不是常数,但总是返回(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非局部.然而,我很好奇:我们如何使内部函数对其参数产生非局部效应?

最佳答案 正如
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).

这将返回(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))
点赞