即使是爸妈的东西,也不能随便动!(讲义)

遗产

一、祖宗的东西可以随便看!某任意层级定义的变量,在当前层级,以及其子层级、孙层级、子子孙孙层级都可以任意查阅(读取)。

x = 'hello world'

def test():
    print('[in test]:', x)

test()
print('[in 全局]:', x)        
[in test]: hello world
[in 全局]: hello world

二、若要处置改动的话,对不起,只能是属于自己的东西。

x = 'hello world'

def test():
    # 即使名字相同,只要试图去改,就独立开辟了属于本级自己的变量。
    x = 'hello python'
    print('[in test]:', x)
        
test()
# 全局的x没有变化
print('[in 全局]:', x)
[in test]: hello python
[in 全局]: hello world

三、若要修改上一级(父级)变量,得采用“nonlocal”明确声明,相当于向父辈申报。

def test():
    x = 'hello world'
    
    def child_test():
        # 声明父级变量将在本级内被修改。
        nonlocal x
        x = 'hello python' 
        print('[in child_test]:', x)
    
    child_test()
    print('[in test]:', x)
    
test()
[in child_test]: hello python
[in test]: hello python

但上述修改有一个前提:要修改的父级变量不是全局变量,或者说其父级所在作用域为非全局作用域才行。

相当于:如果父辈是名人,其遗传下来的东西受保护,需要提交更高级的申报。

# x为全局变量:
x = 'hello world'

def test():
    # nonlocal所在行会出错:SyntaxError: no binding for nonlocal 'x' found
    # 为了防止误改了全局变量,x的父级不允许为全局级。
    nonlocal x
    x = 'hello python'

四、若要修改全局变量,需要在其子层级、孙层级、子子孙孙层级采用“global”明确声明。

# x为全局变量:
x = 'hello world'

def test():
    global x
    x = 'hello python'
    print('[in test]:', x)

test()
print('[in 全局]:', x)
[in test]: hello python
[in 全局]: hello python

总结:

  • 祖宗的东西,可看不可动;
  • 自己的东西,任自己处置;
  • 爸妈的东西,只要他们不是名人,动之前,跟爸妈“nonlocal”招呼一声;
  • 名人祖宗的东西,动之前,必须专门“global”申报。
  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值