
一、祖宗的東西可以隨便看!某任意層級定義的變數,在當前層級,以及其子層級、孫層級、子子孫孫層級都可以任意查閱(讀取),
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”申報,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/242363.html
標籤:其他
上一篇:?超炫100套?vue+echarts大屏可視化資料平臺實戰專案模板 (vue/react 均可使用)
下一篇:二戰結束
