在python的main函數中的變量默認為全局變量,而其他的def函數中的變量則默認為局部變量。
當然,局部變量會優先於全局變量,在執行formal_print(t_global)語句時便可看出。
測試代碼如下:
#!/usr/bin/env python
#coding=utf-8
#測試python的全局變量,局部變量的機制
def formal_print(s_global):
#常規的傳參用法,傳遞參數進行print,變量名可任意
print "formal_print: ", s_global
return
def global_print():
#無參數傳遞,直接對global variable進行print
print "global_print: ", s_global
return
def global_print_para(st):#此處雖然傳遞了一個參數st,但是並沒有在函數中用到
print "global_print_para: ", s_global
return
def test_global():
stest = 'test_global'
print "test_global: ", stest
return
if __name__ == '__main__':
#main函數中聲明的變量默認為global variable,
#而其他def函數中聲明的變量則默認為local variable
s_global = 'global variable s_global'
t_global = 'global variable t_global'
formal_print(s_global)
formal_print(t_global)
global_print()
test_global()
#formal_print(stest)#雖然在test_global()中聲明了變量stest,但stest並非全局變量
print 'End.'