Passing an argument from a parent function to a Python nested function

here is my code:

def f(x):
    def g(n):
        if n < 10:
            x = x + 1
            g(n + 1)
    g(0)

When I evaluate f (0), there will be an error "referenced before destination".

However, when I use "print x" instead of "x = x + 1", it will work.

It seems that in the g area, I can only use x as a β€œuse”, but not a β€œbinding”. I think the problem is that f passes g only the value VALUE x.

Do I understand this correctly? If not, can someone explain why the left side of "x = x + 1" is not defined before the link?

thanks

+2
source share
2 answers

. x Python 2.

Python 3 , nonlocal; , :

def f(x):
    def g(n):
        nonlocal x
        if n < 10:
            x = x + 1
            g(n + 1)
    g(0)

python 2 ; mutable, , (ab) :

def f(x):
    x = [x]   # lists are mutable
    def g(n):
        if n < 10:
            x[0] = x[0] + 1   # not assigning, but mutating (x.__setitem__(0, newvalue))
            g(n + 1)
    g(0)

def f(x):
    def g(n):
        if n < 10:
            g.x = g.x + 1
            g(n + 1)
    g.x = x  # attribute on the function!
    g(0)
+5

, . , , , .

Python 2 " " - global, . Python 3 nonlocal ( ) .

x , ( f). , x g Python 2. Python 3 nonlocal x g.

0

All Articles