命名空間namespace

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()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容