python跨文件使用全局變量的實(shí)現(xiàn)
Python 定義了全局變量的特性,使用global 關(guān)鍵字修飾
global key_word
但是他的一大缺陷就是只能本module 中也就是本文件中使用,跳出這個module就不行。
try 1:
使用一個更宏觀的思路,全局變量就用全局加載的模塊解決,很遺憾也是不行,
file_1:
global a a = "test"
file 2:
import file_1 print(a)
報(bào)錯a沒有定義
try 2:
file_1:
global a a = "test"
file 2:
import file_1 print(file_1.a) file_1.a = "aaa" print(file_1.a)
這樣可以,但是如果再有一個module 想用呢?
try 2:
file_1:
global a a = "test"
file 2:
import file_1 print(file_1.a) file_1.a = "aaa" print(file_1.a)
file 2:
import file_1 import file_2 print(file_1.a) file_1.a = "aaa" print(file_1.a)
這樣就會報(bào)錯,因?yàn)閕mport 加載就會執(zhí)行一遍子module ,兩個module y引用關(guān)系死鎖了。
try 3:
最終使用公共數(shù)據(jù)結(jié)構(gòu)方式解決
file_1:
def init(): global a a = {} def set(arg,value): a[arg] = value def get(arg) return a[arg]
file 2:
import file_1 print(file_1.a) file_1.set("test",(test_value))
file 2:
import file_1 import file_2 file_1.init() print(file_1.get("test"))
思路就是使用一個公共的字典的數(shù)據(jù)結(jié)構(gòu),在主module 中初始化,其他module都應(yīng)用此module,但是不重新初始化字典。
到此這篇關(guān)于python跨文件使用全局變量的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)python跨文件全局變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于numpy.concatenate()函數(shù)的使用及說明
這篇文章主要介紹了關(guān)于numpy.concatenate()函數(shù)的使用及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08Python?Conda安裝包報(bào)錯:PackagesNotFoundError兩種解決方法
這篇文章主要給大家介紹了關(guān)于Python?Conda安裝包報(bào)錯:PackagesNotFoundError的兩種解決方法,這通常意味著安裝程序正在尋找的環(huán)境包沒有在 conda 的默認(rèn)通道中找到,文中將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下2024-06-06Anaconda中更新當(dāng)前環(huán)境的Python版本詳細(xì)步驟
Anaconda是一個開源的Python發(fā)行版本,其包含了conda、Python等180多個科學(xué)包及其依賴項(xiàng),下面這篇文章主要給大家介紹了關(guān)于Anaconda中更新當(dāng)前環(huán)境的Python版本的詳細(xì)步驟,需要的朋友可以參考下2024-08-08scrapy自定義pipeline類實(shí)現(xiàn)將采集數(shù)據(jù)保存到mongodb的方法
這篇文章主要介紹了scrapy自定義pipeline類實(shí)現(xiàn)將采集數(shù)據(jù)保存到mongodb的方法,涉及scrapy采集及操作mongodb數(shù)據(jù)庫的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04