Python強大的自有模塊——標準庫
引言:Python的強大體現在“模塊自信”上,因為Python不僅有很強大的自有模塊(標準庫),還有海量的第三方模塊(或者包、庫),並且很多開發者還在不斷貢獻在自己開發的新模塊(或者包、庫)。本文將向大家概述介紹Python的自有模塊——標準庫。
本文選自《跟老齊學Python:輕鬆入門》。
“Python自帶‘電池’”,這種說法流傳已久。
在Python被安裝的時候,就有不少模塊也隨著安裝到本地的計算機上了。這些東西就如同“電力”一樣,讓Python擁有了無限生機,能夠輕而易舉地免費使用很多模塊。所以,稱其為“自帶電池”。
那些在安裝Python時就默認已經安裝好的模塊被統稱為“標準庫”。
熟悉標準庫是學習編程必須要做的事。
引用的方式
所有模塊都服從下述引用方式,以下是最基本的,也是最常用的,還是可讀性非常好的引用方式。
import modulename
例如:
>>> import pprint
>>> a = {"lang":"python", "book":"www.itdiffer.com", "teacher":"qiwsir", "goal":"from beginner to master"}
>> pprint.pprint(a)
{'book': 'www.itdiffer.com',
'goal': 'from beginner to master',
'lang': 'python',
'teacher': 'qiwsir'}
在對模塊進行說明的過程中,以標準庫pprint為例。
以pprint.pprint()的方式使用模塊中的一種方法,這種方法能夠讓字典格式化輸出。看看結果是不是比原來更容易閱讀了呢?
在import後麵,理論上可以跟好多模塊名稱。但是在實踐中,還是建議大家一次一個名稱,太多了不容易閱讀。
這是用import pprint樣式引入模塊,並以點號“.”(英文半角)的形式引用其方法。
關於引入模塊的方式,前文介紹import語句時已經講過,這裏再次羅列,權當複習。
>>> from pprint import pprint
意思是從pprint模塊中隻將pprint()引入,之後就可以直接使用它了。
>>> pprint(a)
{'book': 'www.itdiffer.com',
'goal': 'from beginner to master',
'lang': 'python',
'teacher': 'qiwsir'}
再懶一些還可以這樣操作:
>>> from pprint import *
這就將pprint模塊中的一切都引入了,於是可以像上麵那樣直接使用模塊中的所有可用的內容。
誠然,如果很明確使用模塊中的哪些方法或屬性,那麼使用類似from modulename import name1, name2, name3...也未嚐不可。需要再次提醒讀者注意的是,不能因為引入了模塊而降低了可讀性,讓別人不知道呈現在眼前的方法是從何而來的。
有時候引入的模塊或者方法名稱有點長,這時可以給它重命名。如:
>>> import pprint as pr
>>> pr.pprint(a)
{'book': 'www.itdiffer.com',
'goal': 'from beginner to master',
'lang': 'python',
'teacher': 'qiwsir'}
當然,還可以這樣操作:
>>> from pprint import pprint as pt
>>> pt(a)
{'book': 'www.itdiffer.com',
'goal': 'from beginner to master',
'lang': 'python',
'teacher': 'qiwsir'}
但是不管怎樣,一定要讓別人看得懂,且要過了若幹時間,自己也還能看得懂。
深入探究
繼續以pprint為例,深入研究:
>>> import pprint
>>> dir(pprint)
['PrettyPrinter', '_StringIO', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_commajoin', '_id', '_len', '_perfcheck', '_recursion', '_safe_repr', '_sorted', '_sys', '_type', 'isreadable', 'isrecursive', 'pformat', 'pprint', 'saferepr', 'warnings']
對dir()並不陌生,從結果中可以看到pprint的屬性和方法。其中有的是以雙畫線、單畫線開頭的,為了不影響我們的視覺,先把它們去掉。
>>> [ m for m in dir(pprint) if not m.startswith('_') ]
['PrettyPrinter', 'isreadable', 'isrecursive', 'pformat', 'pprint', 'saferepr', 'warnings']
針對這幾個,為了能夠搞清楚它們的含義,可以使用help(),比如:
>>> help(isreadable)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'isreadable' is not defined
這樣做是錯誤的。大家知道錯在何處嗎?
>>> help(pprint.isreadable)
前麵是用import pprint方式引入模塊的。
Help on function isreadable in module pprint:
isreadable(object)
Determine if saferepr(object) is readable by eval().
通過幫助信息,能夠查看到該方法的詳細說明。可以用這種方法一個一個地查看,反正也不多,對每個方法都要熟悉。
需要注意的是,pprint.PrettyPrinter是一個類,後麵的是方法。
再回頭看看dir(pprint)的結果:
>>> pprint.__all__
['pprint', 'pformat', 'isreadable', 'isrecursive', 'saferepr', 'PrettyPrinter']
這個結果是不是很眼熟?除了"warnings"之外,跟前麵通過列表解析式得到的結果一樣。
其實,當我們使用from pprint import *的時候,就是將__all__裏麵的方法引入。
幫助、文檔和源碼
你能記住每個模塊的屬性和方法嗎?比如前麵剛剛查詢過的pprint模塊中的屬性和方法,現在能背誦出來嗎?相信大部分人是記不住的。所以,我們需要使用dir()和help()。
>>> print(pprint.__doc__)
Support to pretty-print lists, tuples, & dictionaries recursively.
Very simple, but useful, especially in debugging data structures.
Classes
-------
PrettyPrinter()
Handle pretty-printing operations onto a stream using a configured
set of formatting parameters.
Functions
---------
pformat()
Format a Python object into a pretty-printed representation.
pprint()
Pretty-print a Python object to a stream [default is sys.stdout].
saferepr()
Generate a 'standard' repr()-like value, but protect against recursive
data structures.
pprint.__doc__是查看整個類的文檔,還知道整個文檔是寫在什麼地方的嗎?
還是使用pm.py文件,增加如下內容:
#!/usr/bin/env python
# coding=utf-8
""" #增加的
This is a document of the python module. #增加的
""" #增加的
def lang():
... #省略了,後麵的也省略了
在這個文件的開始部分,所有類、方法和import之前,寫一個用三個引號包裹著的字符串,這就是文檔。
>>> import sys
>>> sys.path.append("~/Documents/VBS/StarterLearningPython/2code")
>>> import pm
>>> print(pm.__doc__)
This is a document of the python module.
這就是撰寫模塊文檔的方法,即在.py文件的最開始寫相應的內容。這個要求應該成為開發者的習慣。
對於Python的標準庫和第三方模塊,不僅可以查看幫助信息和文檔,而且還能夠查看源碼,因為它是開放的。
還是回到dir(pprint)中找一找,有一個__file__屬性,它會告訴我們這個模塊的位置:
>>> print(pprint.__file__)
/usr/lib/python3.4/pprint.py
接下來就可以查看這個文件的源碼:
$ more /usr/lib/python3.4/pprint.py
# Author: Fred L. Drake, Jr.
……
"""Support to pretty-print lists, tuples, & dictionaries recursively.
Very simple, but useful, especially in debugging data structures.
Classes
-------
PrettyPrinter()
Handle pretty-printing operations onto a stream using a configured
set of formatting parameters.
Functions
---------
pformat()
Format a Python object into a pretty-printed representation
.....
"""
這裏隻查抄了文檔中的部分信息,是不是跟前麵通過__doc__查看的結果一樣呢?
請讀者在閑暇時間閱讀源碼。事實證明,這種標準庫中的源碼是質量最好的。閱讀高質量的代碼是提高編程水平的途徑之一。
本文選自《跟老齊學Python:輕鬆入門》,點此鏈接可在博文視點官網查看此書。
想及時獲得更多精彩文章,可在微信中搜索“博文視點”或者掃描下方二維碼並關注。
最後更新:2017-04-01 17:04:39