“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()
的方式應用了一種方法,這種方法能夠讓 dict 格式化輸出。看看結果,是不是比原來更容易閱讀了你?
在 import 后面,理論上可以跟好多模塊名稱。但是在實踐中,我還是建議大家一次一個名稱吧。這樣簡單明了,容易閱讀。
這是用 import pprint
樣式引入模塊,并以 .
點號的形式引用其方法。
還可以:
>>> 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...
也未嘗不可。一再提醒的是不能因為引入了模塊東西而降低了可讀性,讓別人不知道呈現(xiàn)在眼前的方法是從何而來。如果這樣,就要慎用這種方法。
有時候引入的模塊或者方法名稱有點長,可以給它重命名。如:
>>> 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'}
但是不管怎么樣,一定要讓人看懂,過了若干時間,自己也還能看懂。記?。骸败浖芏鄷r候是給人看的,只是偶爾讓機器執(zhí)行”。
繼續(xù)以 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__
里面的方法引入,如果沒有這個,就會將其它所有屬性、方法等引入,包括那些以雙劃線或者單劃線開頭的變量、函數,這些東西事實上很少被在引入模塊時使用。
不知道讀者是否能夠記住看過的上述內容?反正我記不住。所以,我非常喜歡使用 dir() 和 help(),這也是本教程從開始到現(xiàn)在,乃至到以后,總在提倡的方式。
>>> 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__
是查看整個類的文檔,還知道整個文檔是寫在什么地方的嗎?
關于文檔的問題,曾經在《類(5)》、《自省》中有介紹。但是,現(xiàn)在出現(xiàn)的是模塊文檔。
還是使用 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 文件的最開始寫相應的內容。這個要求應該成為開發(fā)習慣。
Python 的模塊,不僅可以看幫助信息和文檔,還能夠查看源碼,因為它是開放的。
還是回頭到 dir(pprint)
中找一找,有一個__file__
,它就告訴我們這個模塊的位置:
>>> print pprint.__file__
/usr/lib/python2.7/pprint.pyc
我是在 ubuntu 中為例,讀者要注意觀察自己的操作系統(tǒng)結果。
雖然是 .pyc 文件,但是不用擔心,根據現(xiàn)實的目錄,找到相應的 .py 文件即可。
$ ls /usr/lib/python2.7/pp*
/usr/lib/python2.7/pprint.py /usr/lib/python2.7/pprint.pyc
果然有一個 pprint.py。打開它,就看到源碼了。
$ cat /usr/lib/python2.7/pprint.py
...
"""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__
查看的結果一樣一樣的呢?
請讀者在閑暇時間,閱讀以下源碼。事實證明,這種標準庫中的源碼是質量最好的。
總目錄 | 上節(jié):編寫模塊 | 下節(jié):標準庫(2)
如果你認為有必要打賞我,請通過支付寶:qiwsir@126.com,不勝感激。