作者sbrhsieh (sbr)
看板Python
標題Re: [問題] 關於全域變數
時間Wed Dec 24 00:12:10 2008
※ 引述《rushcat (嗯)》之銘言:
: 不太懂關於全域變數的用法
: ==============================
: global x
: x = 0
: def A():
: x = 10
: B()
: def B():
: x = 20
: ==============================
: 明明宣告了 x 全域變數
: 但是子程式賦予x的值 似乎僅對子程式裡的x有作用
: 想請問 這樣全域變數的意義是什麼 XD?
: 另外想請問 如果真的需要做全域變數 該怎麼作比較適當!?
global directive 通常不是這樣使用。
global 用在 nested scope 可以讓接下來對被指定的 symbol 作
assignment 的語意改變:
x = 0
def A():
global x
x = 10
B()
def B():
x = 20
print x ### output: 0
A()
print x ### output: 10
如果 function: A 裡沒有
global x statement(應該比較接近 directive),
那麼
x = 10 這個 statement 會把 int object bind 到 function A 執行
時的 local namespace dictionary,而不是 global dictionary。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.136.126
※ 編輯: sbrhsieh 來自: 218.173.136.126 (12/24 00:15)
※ 編輯: sbrhsieh 來自: 218.173.136.126 (12/24 00:29)
推 rushcat:謝謝你!!! 我剛以為我想通了 就刪文了 真不好意思XD 12/24 00:35
→ rushcat:因為習慣寫VB 所以還不太能改變思考模式XD 12/24 00:35
推 cobrasgo:其實最好儘量不要用到global吧,看看能不能包起來 01/02 13:00