命名空间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从外函数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封闭的命名空间中的变量。
        # 当引用某个变量outer_arg的名字时
        # 根据LEGB-rule, local->enclosing->global->built-in。
        # 此时inner_func()的local中找到outer_arg
        # 向外层的outer_func()中查找,从而找到outer_arg并添加到local中
        inner_arg = outer_arg
        print('exit inner_func: %s' % locals())
    # 内函数inner_func()是定义在outer_func()的local中的。
    # 只能在外函数outer_func()执行期间才能运行。
    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()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容