Modify the function variables from inner function in python

前端 未结 3 1557
情话喂你
情话喂你 2020-12-11 20:24

It\'s ok to get and print the outer function variable a

def outer():
    a = 1
    def inner():
        print a

It\'s also ok

相关标签:
3条回答
  • 2020-12-11 21:06

    A generally cleaner way to do this would be:

    def outer():
        a = 1
        def inner(b):
            b += 1
            return b
        a = inner(a)
    

    Python allows a lot, but non-local variables can be generally considered as "dirty" (without going into details here).

    0 讨论(0)
  • 2020-12-11 21:11

    In Python 3 you can do this with the nonlocal keyword. Do nonlocal a at the beginning of inner to mark a as nonlocal.

    In Python 2 it is not possible.

    0 讨论(0)
  • 2020-12-11 21:14

    Workaround for Python 2:

    def outer():
        a = [1]
        def inner():
            a[0] += 1
            print a[0]
    
    0 讨论(0)
提交回复
热议问题