Python全域性變數與global語句

2021-07-26 16:59:18 字數 2209 閱讀 3651

如果將全域性變數的名字宣告在乙個函式體內的時候,全域性變數的名字能被區域性變數給覆蓋掉。

code1:

bar = 100

def foo():

print "\ncalling foo()..."

bar = 200

print "in foo(), bar is", bar

print "in __main__, bar is", bar

foo()

print "\nin __main__, bar is (still)", bar

輸出:

in __main__, bar is 100

calling foo()...

in foo(), bar is 200

in __main__, bar is (still) 100

在foo()函式中區域性的bar將全域性的bar」覆蓋掉了」。

code2:

bar = 100

def foo():

print "\ncalling foo()..."

#bar = 200

print "in foo(), bar is", bar

if __name__ == '__main__' :

print "in __main__, bar is", bar

foo()

print "\nin __main__, bar is (still)", bar

輸出:

in __main__, bar is 100

calling foo()...

in foo(), bar is 100

in __main__, bar is (still) 100

這裡將foo()函式內對bar賦值語句注釋掉,發現函式內部可以訪問全域性的bar。

code 3:

bar = 100

def foo():

print "\ncalling foo()..."

bar += 1

print "in foo(), bar is", bar

if __name__ == '__main__' :

print "in __main__, bar is", bar

foo()

print "\nin __main__, bar is (still)", bar

輸出:

in __main__, bar is 100

calling foo()...

traceback (most recent call last):

file "/home/zhangjun/workspace/try/src/try.py", line 10, in foo()

file "/home/zhangjun/workspace/try/src/try.py", line 5, in foo

bar += 1

unboundlocalerror: local variable 'bar' referenced before assignment

這裡在foo()函式內部,對bar變數值進行修改,發現修改的其實被視為乙個區域性變數。

code 4:

bar = 100

def foo():

print "\ncalling foo()..."

global bar

bar += 1

print "in foo(), bar is", bar

if __name__ == '__main__' :

print "in __main__, bar is", bar

foo()

print "\nin __main__, bar is (still)", bar

輸出:

in __main__, bar is 100

calling foo()...

in foo(), bar is 101

in __main__, bar is (still) 101

此時,在foo()函式內,我們首先對變數bar進行global宣告,這樣就可以順利修改這個全域性變數了。

全域性變數global與超全域性變數 GLOBALS

出錯行 mysqli query link,select from sys calendar where id id link為連線資料庫,此處為空。解決方法 link不能從global獲取,改為 globals link mysqli query globals link select from ...

python 全域性變數

應該盡量避免使用全域性變數。不同的模組都可以自由的訪問全域性變數,可能會導致全域性變數的不可預知性。對全域性變數,如果程式設計師甲修改了 a的值,程式設計師乙同時也要使用 a,這時可能導致程式中的錯誤。這種錯誤是很難發現和更正的。全域性變數降低了函式或模組之間的通用性,不同的函式或模組都要依賴於全域...

Python 全域性變數

應該盡量避免使用全域性變數。不同的模組都可以自由的訪問全域性變數,可能會導致全域性變數的不可預知性。對全域性變數,如果程式設計師甲修改了 a的值,程式設計師乙同時也要使用 a,這時可能導致程式中的錯誤。這種錯誤是很難發現和更正的。全域性變數降低了函式或模組之間的通用性,不同的函式或模組都要依賴於全域...