2015-09-17 22 views
0

我對Python的一些行爲感到困惑。我一直認爲導入一個模塊基本上意味着執行它。 (就像他們在這裏說:Does python execute imports on importation)所以我創建了三個簡單的腳本來測試一些:從其他不同模塊導入一個模塊只執行一次。爲什麼?

main.py

import config 
print(config.a) 

config.a += 1 
print(config.a) 

import test 
print(config.a) 

config.py

def get_a(): 
    print("get_a is called") 
    return 1 
a = get_a() 

test.py

import config 
print(config.a) 
config.a += 1 

運行main.py時的輸出爲:

get_a is called 
1 
2 
2 
3 

現在我很困惑,因爲我期望get_a()被稱爲兩次,一次從main.py和一次從test.py。有人可以解釋爲什麼它不是?如果我真的想第二次導入配置文件,就像在a=1開頭那樣?

(幸運的是,對於我的項目來說,這種行爲正是我想要的,因爲get_a()對應於一個函數,它讀取數據庫中的大量數據,當然我只想讀一次,但應該可以從多個模塊)。

回答

1

因爲配置模塊已經加載,所以不需要'運行'了,只需返回加載的實例即可。

某些標準庫模塊使用此示例,例如random。它在第一次導入時創建一個類Random的對象,並在再次導入時重新使用它。對模塊的評論如下:

# Create one instance, seeded from current time, and export its methods 
# as module-level functions. The functions share state across all uses 
#(both in the user's code and in the Python libraries), but that's fine 
# for most programs and is easier for the casual user than making them 
# instantiate their own Random() instance. 
相關問題