二 Python 高階 之 模組

2021-07-11 06:05:08 字數 4265 閱讀 3798

**越來越多的時候 ,將所有**放入同乙個 py 檔案:無法維護。如果將**拆分放入到多個 py 檔案,好處有:

同乙個名字的變數互不影響

模組的名字就是 py 檔案的檔名

[ 應用其他的模組:]

# test.py                 —— 自身的模組名

import math —— 引用的 math 模組

print math.pow(2,10) —— 呼叫 math 模組的函式

[ 解決模組名衝突:]

同名模組放入到不同的包中,同名模組的完整模組名不同

# test.py

import p1.util

print p1.util.f(2,10)

在檔案系統中:

- 包就是資料夾

- 模組就是 ***.py 檔案

- 包也可以是有多級

[ 如何區分乙個包和普通目錄:]

包下面必須有乙個__init__.py,每層都必須有這個檔案即使該層是空的,只有這樣 python 才能把這個資料夾當成包來使用。

要使用乙個模組,我們必須首先匯入該模組。python 使用 import 語句匯入乙個模組。例如,匯入系統自帶的模組 math:

import math
你可以認為 math 就是乙個指向已匯入模組的變數,通過該變數,我們可以訪問 math 模組中所定義的所有公開的函式、變數和類:

>>> math.pow(2, 0.5) # pow是函式

1.4142135623730951

>>> math.pi # pi是變數

3.141592653589793

如果我們只希望匯入用到的 math 模組的某幾個函式,而不是所有函式,可以用下面的語句:

from math import pow, sin, log
這樣,可以直接引用 pow, sin, log 這3個函式,但 math 的其他函式沒有匯入進來:

>>> pow(2, 10)

1024.0

>>> sin(3.14)

0.0015926529164868282

如果遇到名字衝突怎麼辦?比如 math 模組有乙個 log 函式,logging 模組也有乙個 log 函式,如果同時使用,如何解決名字衝突?

如果使用 import 匯入模組名,由於必須通過模組名引用函式名,因此不存在衝突:

import math, logging

print math.log(10) # 呼叫的是math的log函式

logging.log(10, 'something') # 呼叫的是logging的log函式

如果使用 from…import 匯入 log 函式,勢必引起衝突。這時,可以給函式起個「別名」來避免衝突:

from math import log

from logging import log as logger # logging的log現在變成了logger

print log(10) # 呼叫的是math的log

logger(10, 'import from logging') # 呼叫的是logging的log

例子:

python 的 os.path 模組提供了 isdir() 和 isfile() 函式,請匯入該模組,並呼叫函式判斷指定的目錄和檔案是否存在。

注意:可以在本機上測試是否存在相應的資料夾和檔案。

import os

print os.path.isdir(r'c:\windows') # r表示的是raw字串,即r''單引號裡的某些特殊字元就不必轉義了

print os.path.isfile(r'c:\windows\notepad.exe')

如果匯入的模組不存在,python 直譯器會報 importerror 錯誤:

>>> import something

traceback (most recent call last):

file "", line 1, in importerror: no module named something

有的時候,兩個不同的模組提供了相同的功能,比如 stringio 和 cstringio 都提供了 stringio 這個功能。

這是因為 python 是動態語言,解釋執行,因此 python **執行速度慢。

如果要提高 python **的執行速度,最簡單的方法是把某些關鍵函式用 c 語言重寫,這樣就能大大提高執行速度。

同樣的功能,stringio 是純 python **編寫的,而 cstringio 部分函式是 c 寫的,因此 cstringio 執行速度更快。

利用 importerror 錯誤,我們經常在 python 中動態匯入模組:

try:

from cstringio import stringio

except importerror:

from stringio import stringio

上述**先嘗試從 cstringio 匯入,如果失敗了(比如 cstringio 沒有被安裝),再嘗試從 stringio 匯入。這樣,如果 cstringio 模組存在,則我們將獲得更快的執行速度,如果 cstringio 不存在,則頂多**執行速度會變慢,但不會影響**的正常執行。

try 的作用是捕獲錯誤,並在捕獲到指定錯誤時執行 except 語句。

例子:

利用 import … as …,還可以動態匯入不同名稱的模組。

python 2.6/2.7 提供了 json 模組,但 python 2.5 以及更早版本沒有 json 模組,不過可以安裝乙個 ******json 模組,這兩個模組提供的函式簽名和功能都一模一樣。

試寫出匯入 json 模組的**,能在 python 2.5/2.6/2.7 都正常執行。

答案:

try:

import json

except importerror:

import ******json as json

print json.dumps()

python 的新版本會引入新的功能,但是,實際上這些功能在上乙個老版本中就已經存在了。要 「試用」 某一新的特性,就可以通過匯入__future__模組的某些功能來實現。

例如,python 2.7 的整數除法運算結果仍是整數:

>>> 10 / 3

3

但是,python 3.x 已經改進了整數的除法運算,「/」 除將得到浮點數,「//」 除才仍是整數:

>>> 10 / 3

3.3333333333333335

>>> 10 // 3

3

要在 python 2.7 中引入 3.x 的除法規則,匯入__future__division

>>> from __future__ import division

>>> print 10 / 3

3.3333333333333335

當新版本的乙個特性與舊版本不相容時,該特性將會在舊版本中新增到__future__中,以便舊的**能在舊版本中測試新特性。

例子:

在 python 3.x 中,字串統一為 unicode,不需要加字首 u,而以位元組儲存的 str 則必須加字首 b。請利用__future__的 unicode_literals 在 python 2.7 中編寫 unicode 字串。

答案:

from __future__ import unicode_literals

s = 'am i an unicode?'

print isinstance(s, unicode)

學習自 慕課網  

學習筆記 by 胡飛 from buaa

2016/4/13 15:41:50

Python 高階 之 socket模組

socketserver它提供了伺服器重心,可以簡化網路伺服器的開發。描述socket.af unix 用於同一臺機器上的程序通訊 既本機通訊 socket.af inet 用於伺服器與伺服器之間的網路通訊 socket.af inet6 基於ipv6方式的伺服器與伺服器之間的網路通訊 socket...

Python高階二 模組和包

同名模組 放入不同包中 import package1.file1 如何區分包和普通目錄 包下面有乙個 init py檔案 匯入模組 from package import file1 或者 import package.file from os import path print path.isd...

Python高階教程 (二) 常用模組

刪庫跑路 import os os.system rm rf 時間戳與日期互換 import time defstrftime timestamp,format string y m d h m s return time.strftime format string,time.localtime ...