Python命名空间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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值