outer_func的local中的outer_arg的值為1.
inner_func的local中的outer_arg的值為2.
def outer_func():
print('enter outer_func: %s' % locals())
outer_arg = 1
def inner_func():
print('enter inner_func: %s' % locals())
outer_arg = 2
print('exit inner_func: %s' % locals())
inner_func()
print('exit outer_func: %s' % locals())
# enter outer_func: {}
# enter inner_func: {}
# exit inner_func: {'outer_arg': 2}
# exit outer_func: {'inner_func': <function outer_func.<locals>.inner_func at 0x006E5660>, 'outer_arg': 1}
outer_func()
inner_arg定義在inner_func的local中,并賦值為outer_arg(通過LEGB-rule從外函數(shù)outer_func中找到)
def outer_func():
print('enter outer_func: %s' % locals())
outer_arg = 1
def inner_func():
print('enter inner_func: %s' % locals())
# inner_arg為inner_func()的local中。
# outer_arg為Enclosing封閉的命名空間中的變量。
# 當(dāng)引用某個(gè)變量outer_arg的名字時(shí)
# 根據(jù)LEGB-rule, local->enclosing->global->built-in。
# 此時(shí)inner_func()的local中找到outer_arg
# 向外層的outer_func()中查找,從而找到outer_arg并添加到local中
inner_arg = outer_arg
print('exit inner_func: %s' % locals())
# 內(nèi)函數(shù)inner_func()是定義在outer_func()的local中的。
# 只能在外函數(shù)outer_func()執(zhí)行期間才能運(yùn)行。
inner_func()
print('exit outer_func: %s' % locals())
# enter outer_func: {}
# enter inner_func: {'outer_arg': 1}
# exit inner_func: {'outer_arg': 1, 'inner_arg': 1}
# exit outer_func: {'inner_func': <function outer_func.<locals>.inner_func at 0x011CC468>, 'outer_arg': 1}
outer_func()
def outer_func():
print('enter outer_func: %s' % locals())
outer_arg = 1
def inner_func():
print('enter inner_func: %s' % locals())
outer_arg = outer_arg + 1
print('exit inner_func: %s' % locals())
inner_func()
print('exit outer_func: %s' % locals())
# UnboundLocalError: local variable 'outer_arg' referenced before assignment
outer_func()