python跨文件使用全局變量的實(shí)現(xiàn)
Python 定義了全局變量的特性,使用global 關(guān)鍵字修飾
global key_word
但是他的一大缺陷就是只能本module 中也就是本文件中使用,跳出這個(gè)module就不行。
try 1:使用一個(gè)更宏觀的思路,全局變量就用全局加載的模塊解決,很遺憾也是不行,
file_1:
global aa = 'test'
file 2:
import file_1print(a)
報(bào)錯(cuò)a沒(méi)有定義try 2:file_1:
global aa = 'test'
file 2:
import file_1print(file_1.a)file_1.a = 'aaa'print(file_1.a)
這樣可以,但是如果再有一個(gè)module 想用呢?try 2:file_1:
global aa = 'test'
file 2:
import file_1print(file_1.a)file_1.a = 'aaa'print(file_1.a)
file 2:
import file_1import file_2print(file_1.a)file_1.a = 'aaa'print(file_1.a)
這樣就會(huì)報(bào)錯(cuò),因?yàn)閕mport 加載就會(huì)執(zhí)行一遍子module ,兩個(gè)module y引用關(guān)系死鎖了。
try 3: 最終使用公共數(shù)據(jù)結(jié)構(gòu)方式解決
file_1:
def init(): global a a = {}def set(arg,value): a[arg] = valuedef get(arg) return a[arg]
file 2:
import file_1print(file_1.a)file_1.set('test',(test_value))
file 2:
import file_1import file_2file_1.init()print(file_1.get('test'))
思路就是使用一個(gè)公共的字典的數(shù)據(jù)結(jié)構(gòu),在主module 中初始化,其他module都應(yīng)用此module,但是不重新初始化字典。
到此這篇關(guān)于python跨文件使用全局變量的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)python跨文件全局變量?jī)?nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式2. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))3. python web框架的總結(jié)4. 詳解Python模塊化編程與裝飾器5. Python通過(guò)format函數(shù)格式化顯示值6. html小技巧之td,div標(biāo)簽里內(nèi)容不換行7. python裝飾器三種裝飾模式的簡(jiǎn)單分析8. Python如何進(jìn)行時(shí)間處理9. Python實(shí)現(xiàn)迪杰斯特拉算法過(guò)程解析10. python使用ctypes庫(kù)調(diào)用DLL動(dòng)態(tài)鏈接庫(kù)
