一、祖宗的东西可以随便看!某任意层级定义的变量,在当前层级,以及其子层级、孙层级、子子孙孙层级都可以任意查阅(读取)。
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”申报。