在 python 裡,區域性的觀念很嚴重。
如果要宣告使用 global 變數,可以這麼做:
-----code 1--------
def f2():
global b
b = 1
print "in f2", b
global b
b = 1
print "in f2", b
b = 2
print "out of f2 1st time=", b
print "out of f2 1st time=", b
f2()
print "out of f2 2nd time=", b
-------------
結果為:
-------------
out of f2 1st time= 2
in f2 1
out of f2 2nd time= 1
in f2 1
out of f2 2nd time= 1
-------------
如果程式碼長這樣
-------------
a = 1
def f1():
a = 2
print "in f1", a
a = 2
print "in f1", a
print "out of f1 1st time=", a
f1()
print "out of f1 2nd time=", a
-------------
執行完結果是:
-------------
out of f1 1st time= 1
in f1 2
out of f1 2nd time= 1
in f1 2
out of f1 2nd time= 1
-------------
如果是在 VB,在有宣告的情況下,應該會是以下的結果
--
out of f1 1st time= 1
in f1 2
out of f1 2nd time= 2
in f1 2
out of f1 2nd time= 2
--
針對 code 1,
有幾點要提醒的
一、global 是放在較裡面的block裡,不是放在較外面的block裡。用意應該是跟編譯器講,請找外面的變數,不要找裡面的變數。這跟 VB 只要在外面宣告或是直接宣告global就可以用的想法不太一樣。
二、python 是 script,所以在程式碼裡要 call function 之前,該 function 要先宣告。所以 def f2 一定要在 f2() 敘述之前。否則會出問題。這一點也跟 VB 不一樣。所以我想有個「把 function 定義都放在.py 的前面」習慣,會是比較好的。
請先 登入 以發表留言。