命名空间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': .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': .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()

你可能感兴趣的:(命名空间namespace)