Re: [問題] 拿別的檔案的global變數會有問題

看板Python作者 (sbr)時間16年前 (2009/07/23 20:00), 編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《iqiq (哈哈哈)》之銘言: : 我的code如下 : 我想要在self.a.Test()執行完後,print出123數值 : 但都辦不到(只會印出0) : 要怎樣在A.py裡面拿到main.py中kkkkk已經改變過的數值呢? : -------------------------------------------------------- : main.py: : import A : kkkkk = 0 : def SetAAPP(num): : global kkkkk : kkkkk = num : def GetAAPP(): : global kkkkk : return kkkkk : class B: : def __init__(self): : pass : def Initial(self): : self.a = A.A() : self.a.Test() : if __name__ == "__main__": : b = B(); : SetAAPP(123) : b.Initial(); : A.py: : import main : class A: : def __init__(self): : pass : def Test(self): : aaaaa = main.kkkkk : print aaaaa 上述程式碼的作法,當一個 A instance 執行 Test method 時的確是可以存取 module 'main' 的 kkkkk member。 那你的問題在於,你透過 Python interpreter 直接去執行 main.py 時,main.py 被載入成為 module '__main__' 而不是 module 'main'。也就是說當你這樣子 執行 main.py 時: python main.py main.py 會被載入並執行成為 module '__main__',在載入這個 module 時會 導致 A.py 被載入成為 module 'A',而 module 'A' 載入過程又會去載入一次 main.py 檔成為 module 'main'。module '__main__' 載入時執行了: b = B() SetAAPP(123) b.Initial() SetAAPP(123) statement 執行過後 module '__main__' 的 member: kkkkk 的 值會變更為 123,但是 module 'A' 載入過程去載入的 module 'main' 的 member: kkkkk 在 module 'main' 載入後就沒有變更過(值為 0)。 如果你不能了解我上述在講什麼,你可以試著把 main.py 改成如下: import A kkkkk = 0 def SetAAPP(num): global kkkkk kkkkk = num def GetAAPP(): global kkkkk return kkkkk class B: def __init__(self): pass def Initial(self): self.a = A.A() self.a.Test() def info(): import sys # main.py is loaded twice as module __main__ and module main. print sys.modules['__main__'].kkkkk, sys.modules['main'].kkkkk def main(): b = B() SetAAPP(123) b.Initial() if __name__ == "__main__": main() info() 以 python main.py 來執行時,會獲得這樣子的輸出: 0 123 0 如果你執行 python.exe,然後執行以下的 statements: import main main.main() 輸出就是: 123 一如你原先設計所要的效果。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.139.59 ※ 編輯: sbrhsieh 來自: 218.173.139.59 (07/23 20:03) ※ 編輯: sbrhsieh 來自: 218.173.139.59 (07/23 23:15)

07/24 00:32, , 1F
it work! 太感謝了~~~ ^_^
07/24 00:32, 1F

07/24 02:57, , 2F
原來如此 o.O
07/24 02:57, 2F
文章代碼(AID): #1AQ53fpP (Python)
文章代碼(AID): #1AQ53fpP (Python)