Passing argument from Parent function to nested function Python

后端 未结 2 1652
有刺的猬
有刺的猬 2020-11-30 14:40

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), th

2条回答
  •  眼角桃花
    2020-11-30 15:33

    Yes, assigning to names is different than reading their values. Any names that are assigned to in a function are considered local variables of that function unless you specify otherwise.

    In Python 2, the only way to "specify otherwise" is to use a global statement to allow you assign to a global variable. In Python 3, you also have the nonlocal statement to assign a value to a variable in a higher (but not necessarily global) scope.

    In your example, x is in a higher but non-global scope (the function f). So there is no way to assign to x from within g in Python 2. In Python 3 you could do it with a nonlocal x statement in g.

提交回复
热议问题