python模組之模組用於定義

2021-07-30 04:43:33 字數 1112 閱讀 3260

任何python程式都可以作為模組匯入;

通過python idle執行儲存在資料夾中的檔案:

這裡是告訴編譯器,除了從預設的目錄中查詢外,還要從d:\program files (x86)\python3.5中查詢模組;

生成的.pyc檔案是(平台無關的)經過處理(編譯)的,已經轉換成python能夠更加處理的檔案,如果再匯入相同的模組,匯入的是.pyc檔案,而不是.py檔案;

如果再次匯入,就什麼也不會發生了:

這些內容只需要定義一次,所以匯入多次效果與匯入一次是相同的。

如果希望重新匯入生效,python2中還有另外一種方法:hello = reload(hello),python3已經去掉了該方法。

在模組中定義函式(主要用於**重用):

#hello.py

def hello():

print ('hello nannan!!')

執行:模組被用來定義函式,類和其他一些內容,但是,有時候在模組中需要新增一些檢查模組本身是否能正常工作的測試**。

#hello.py

def hello():

print ('hello nannan!!')

#a test

hello()

如果將其作為模組匯入,會出現下面的情況:

匯入時執行了一遍方法,然後呼叫時又執行了一遍方法。

可以使用下面的方式解決上面的問題:

#hello.py

def hello():

print ('hello nannan!!')

def test():

hello()

if __name__ == '__main__':test()

然後進行執行:

所以得出:

避免匯入時執行內容,需要使用變數__name__;

__name__變數的預設值為'__main__';

而在匯入模組時,這個值被賦值為模組名,所以在檔案中加入**:if __name__ == '__main__':test(),在非匯入模組時,會執行test()方法,將模組進行匯入時,name被賦值為模組名,test()方法測試**將不被執行。

python模組 python自定義模組

1.import 模組名 匯入模組中的所有內容 引入多個用逗號分隔 import random,time 2.from 模組名 import 函式名1,函式名2.匯入部分模組 匯入部分的話直接使用 3.from 模組名 import 匯入所有,有約束 需要在 init py檔案中新增屬性 all 函...

python模組之shutil模組

高階的 檔案 資料夾 壓縮包 處理模組 shutil.copyfileobj fsrc,fdst length 將檔案內容拷貝到另乙個檔案中 import shutil shutil.copyfileobj open old.xml r open new.xml w shutil.copyfile ...

python模組之timeit模組

timeit模組用來測量函式執行時間,通過實際 學習怎樣應用timeit模組 fromtimeitimport print timeit x 7 print timeit x 7 number 1000000 print timeit x 7 number 1000000 print 上面三個列印說...