“python自帶‘電池’”,聽說過這種說法嗎?
在python被安裝的時候,就有不少模塊也隨著安裝到本地的計算機上了。這些東西就如同“能源”、“電力”一樣,讓python擁有了無限生機,能夠非常輕而易舉地免費使用很多模塊。所以,稱之為“自帶電池”。
它們被稱為“標準庫”。
熟悉標準庫,是進行編程的必須。
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/220.md#引用的方式)引用的方式
不僅使標準庫的模塊,所有模塊都服從下述引用方式。
最基本的、也是最常用的,還是可讀性非常好的:
~~~
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...`也未嘗不可。一再提醒的是不能因為引入了模塊東西而降低了可讀性,讓別人不知道呈現在眼前的方法是從何而來。如果這樣,就要慎用這種方法。
有時候引入的模塊或者方法名稱有點長,可以給它重命名。如:
~~~
>>> 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'}
~~~
但是不管怎么樣,一定要讓人看懂,過了若干時間,自己也還能看懂。記住:“軟件很多時候是給人看的,只是偶爾讓機器執行”。
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/220.md#深入探究)深入探究
繼續以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__`里面的方法引入,如果沒有這個,就會將其它所有屬性、方法等引入,包括那些以雙劃線或者單劃線開頭的變量、函數,這些東西事實上很少被在引入模塊時使用。
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/220.md#幫助文檔和源碼)幫助、文檔和源碼
不知道讀者是否能夠記住看過的上述內容?反正我記不住。所以,我非常喜歡使用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__`是查看整個類的文檔,還知道整個文檔是寫在什么地方的嗎?
關于文檔的問題,曾經在[《類(5)》](https://github.com/qiwsir/StarterLearningPython/blob/master/210.md)、[《自省》](https://github.com/qiwsir/StarterLearningPython/blob/master/130.md)中有介紹。但是,現在出現的是模塊文檔。
還是使用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/python2.7/pprint.pyc
~~~
我是在ubuntu中為例,讀者要注意觀察自己的操作系統結果。
雖然是.pyc文件,但是不用擔心,根據現實的目錄,找到相應的.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__`查看的結果一樣一樣的呢?
請讀者在閑暇時間,閱讀以下源碼。事實證明,這種標準庫中的源碼是質量最好的。
- 第零章 預備
- 關于Python的故事
- 從小工到專家
- Python安裝
- 集成開發環境
- 第壹章 基本數據類型
- 數和四則運算
- 除法
- 常用數學函數和運算優先級
- 寫一個簡單的程序
- 字符串(1)
- 字符串(2)
- 字符串(3)
- 字符串(4)
- 字符編碼
- 列表(1)
- 列表(2)
- 列表(3)
- 回顧list和str
- 元組
- 字典(1)
- 字典(2)
- 集合(1)
- 集合(2)
- 第貳章 語句和文件
- 運算符
- 語句(1)
- 語句(2)
- 語句(3)
- 語句(4)
- 語句(5)
- 文件(1)
- 文件(2)
- 迭代
- 練習
- 自省
- 第叁章 函數
- 函數(1)
- 函數(2)
- 函數(3)
- 函數(4)
- 函數練習
- 第肆章 類
- 類(1)
- 類(2)
- 類(3)
- 類(4)
- 類(5)
- 多態和封裝
- 特殊方法(1)
- 特殊方法(2)
- 迭代器
- 生成器
- 上下文管理器
- 第伍章 錯誤和異常
- 錯誤和異常(1)
- 錯誤和異常(2)
- 錯誤和異常(3)
- 第陸章 模塊
- 編寫模塊
- 標準庫(1)
- 標準庫(2)
- 標準庫(3)
- 標準庫(4)
- 標準庫(5)
- 標準庫(6)
- 標準庫(7)
- 標準庫(8)
- 第三方庫
- 第柒章 保存數據
- 將數據存入文件
- mysql數據庫(1)
- MySQL數據庫(2)
- mongodb數據庫(1)
- SQLite數據庫
- 電子表格
- 第捌章 用Tornado做網站
- 為做網站而準備
- 分析Hello
- 用tornado做網站(1)
- 用tornado做網站(2)
- 用tornado做網站(3)
- 用tornado做網站(4)
- 用tornado做網站(5)
- 用tornado做網站(6)
- 用tornado做網站(7)
- 第玖章 科學計算
- 為計算做準備
- Pandas使用(1)
- Pandas使用(2)
- 處理股票數據
- 附:網絡文摘
- 如何成為Python高手
- ASCII、Unicode、GBK和UTF-8字符編碼的區別聯系