Skip to content

Commit 6cd844d

Browse files
committed
library
1 parent 08be13a commit 6cd844d

4 files changed

Lines changed: 231 additions & 1 deletion

File tree

219.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,6 @@ python不是一个封闭的体系,是一个开放系统。开放系统的最
188188

189189
------
190190

191-
[总目录](./index.md)   |   [上节:错误和异常(3)](./218.md)   |   [下节:](./220.md)
191+
[总目录](./index.md)   |   [上节:错误和异常(3)](./218.md)   |   [下节:标准库(1)](./220.md)
192192

193193
如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。

220.md

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
>一切苦毒、恼恨、忿怒、嚷闹、毁谤,并一切的恶毒,都当从你们中间除掉。并要以恩慈相待,存怜悯的心,彼此饶恕,正如神在基督里饶恕了你们一样(EPHESIANS 4:31-32)
2+
3+
#标准库(1)
4+
5+
“python自带‘电池’”,听说过这种说法吗?
6+
7+
在python被安装的时候,就有不少模块也随着安装到本地的计算机上了。这些东西就如同“能源”、“电力”一样,让python拥有了无限生机,能够非常轻而易举地免费使用很多模块。所以,称之为“自带电池”。
8+
9+
它们被称为“标准库”。
10+
11+
熟悉标准库,是进行编程的必须。
12+
13+
##引用的方式
14+
15+
不仅使标准库的模块,所有模块都服从下述引用方式。
16+
17+
最基本的、也是最常用的,还是可读性非常好的:
18+
19+
import modulename
20+
21+
例如:
22+
23+
>>> import pprint
24+
>>> a = {"lang":"python", "book":"www.itdiffer.com", "teacher":"qiwsir", "goal":"from beginner to master"}
25+
>>> pprint.pprint(a)
26+
{'book': 'www.itdiffer.com',
27+
'goal': 'from beginner to master',
28+
'lang': 'python',
29+
'teacher': 'qiwsir'}
30+
31+
在对模块进行说明的过程中,我以标准库pprint为例。以`pprint.pprint()`的方式应用了一种方法,这种方法能够让dict格式化输出。看看结果,是不是比原来更容易阅读了你?
32+
33+
在import后面,理论上可以跟好多模块名称。但是在实践中,我还是建议大家一次一个名称吧。这样简单明了,容易阅读。
34+
35+
这是用`import pprint`样式引入模块,并以`.`点号的形式引用其方法。
36+
37+
还可以:
38+
39+
>>> from pprint import pprint
40+
41+
意思是从`pprint`模块中之将`pprint()`引入,然后就可以这样来应用它:
42+
43+
>>> pprint(a)
44+
{'book': 'www.itdiffer.com',
45+
'goal': 'from beginner to master',
46+
'lang': 'python',
47+
'teacher': 'qiwsir'}
48+
49+
再懒惰一些,可以:
50+
51+
>>> from pprint import *
52+
53+
这就将pprint模块中的一切都引入了,于是可以像上面那样直接使用每个函数。但是,这样造成的结果是可读性不是很好,并且,有用没用的都拿过来,是不是太贪婪了?贪婪的结果是内存就消耗了不少。所以,这种方法,可以用于常用并且模块属性或方法不是很多的情况。
54+
55+
诚然,如果很明确使用那几个,那么使用类似`from modulename import name1, name2, name3...`也未尝不可。一再提醒的是不能因为引入了模块东西而降低了可读性,让别人不知道呈现在眼前的方法是从何而来。如果这样,就要慎用这种方法。
56+
57+
有时候引入的模块或者方法名称有点长,可以给它重命名。如:
58+
59+
>>> import pprint as pr
60+
>>> pr.pprint(a)
61+
{'book': 'www.itdiffer.com',
62+
'goal': 'from beginner to master',
63+
'lang': 'python',
64+
'teacher': 'qiwsir'}
65+
66+
当然,还可以这样:
67+
68+
>>> from pprint import pprint as pt
69+
>>> pt(a)
70+
{'book': 'www.itdiffer.com',
71+
'goal': 'from beginner to master',
72+
'lang': 'python',
73+
'teacher': 'qiwsir'}
74+
75+
但是不管怎么样,一定要让人看懂,过了若干时间,自己也还能看懂。记住:“软件很多时候是给人看的,只是偶尔让机器执行”。
76+
77+
##深入探究
78+
79+
继续以pprint为例,深入研究:
80+
81+
>>> import pprint
82+
>>> dir(pprint)
83+
['PrettyPrinter', '_StringIO', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_commajoin', '_id', '_len', '_perfcheck', '_recursion', '_safe_repr', '_sorted', '_sys', '_type', 'isreadable', 'isrecursive', 'pformat', 'pprint', 'saferepr', 'warnings']
84+
85+
对dir()并不陌生。从结果中可以看到pprint的属性和方法。其中有不少是双划线、电话线开头的。为了不影响我们的视觉,先把它们去掉。
86+
87+
>>> [ m for m in dir(pprint) if not m.startswith('_') ]
88+
['PrettyPrinter', 'isreadable', 'isrecursive', 'pformat', 'pprint', 'saferepr', 'warnings']
89+
90+
对这几个,为了能够搞清楚它们的含义,可以使用`help()`,比如:
91+
92+
>>> help(isreadable)
93+
Traceback (most recent call last):
94+
File "<stdin>", line 1, in <module>
95+
NameError: name 'isreadable' is not defined
96+
97+
这样做是错误的。知道错在何处吗?
98+
99+
>>> help(pprint.isreadable)
100+
101+
别忘记了,我前面是用`import pprint`方式引入模块的。
102+
103+
Help on function isreadable in module pprint:
104+
105+
isreadable(object)
106+
Determine if saferepr(object) is readable by eval().
107+
108+
通过帮助信息,能够查看到该方法的详细说明。可以用这种方法一个一个地查过来,反正也不多,对每个方法都熟悉一些。
109+
110+
注意的是`pprint.PrettyPrinter`是一个类,后面的是函数(方法)。
111+
112+
在回头看看`dir(pprint)`的结果,关注一个:
113+
114+
>>> pprint.__all__
115+
['pprint', 'pformat', 'isreadable', 'isrecursive', 'saferepr', 'PrettyPrinter']
116+
117+
这个结果是不是眼熟?除了"warnings",跟前面通过列表解析式得到的结果一样。
118+
119+
其实,当我们使用`from pprint import *`的时候,就是将`__all__`里面的方法引入,如果没有这个,就会将其它所有属性、方法等引入,包括那些以双划线或者单划线开头的变量、函数,这些东西事实上很少被在引入模块时使用。
120+
121+
##帮助、文档和源码
122+
123+
不知道读者是否能够记住看过的上述内容?反正我记不住。所以,我非常喜欢使用dir()和help(),这也是本教程从开始到现在,乃至到以后,总在提倡的方式。
124+
125+
>>> print pprint.__doc__
126+
Support to pretty-print lists, tuples, & dictionaries recursively.
127+
128+
Very simple, but useful, especially in debugging data structures.
129+
130+
Classes
131+
-------
132+
133+
PrettyPrinter()
134+
Handle pretty-printing operations onto a stream using a configured
135+
set of formatting parameters.
136+
137+
Functions
138+
---------
139+
140+
pformat()
141+
Format a Python object into a pretty-printed representation.
142+
143+
pprint()
144+
Pretty-print a Python object to a stream [default is sys.stdout].
145+
146+
saferepr()
147+
Generate a 'standard' repr()-like value, but protect against recursive
148+
data structures.
149+
150+
`pprint.__doc__`是查看整个类的文档,还知道整个文档是写在什么地方的吗?
151+
152+
关于文档的问题,曾经在[《类(5)》](./210.md)[《自省》](./130.md)中有介绍。但是,现在出现的是模块文档。
153+
154+
还是使用pm.py那个文件,增加如下内容:
155+
156+
#!/usr/bin/env python
157+
# coding=utf-8
158+
159+
""" #增加的
160+
This is a document of the python module. #增加的
161+
""" #增加的
162+
163+
def lang():
164+
... #省略了,后面的也省略了
165+
166+
在这个文件的开始部分,所有类和方法、以及import之前,写一个用三个引号包括的字符串。那就是文档。
167+
168+
>>> import sys
169+
>>> sys.path.append("~/Documents/VBS/StarterLearningPython/2code")
170+
>>> import pm
171+
>>> print pm.__doc__
172+
173+
This is a document of the python module.
174+
175+
这就是撰写模块文档的方法,即在.py文件的最开始写相应的内容。这个要求应该成为开发习惯。
176+
177+
python的模块,不仅可以看帮助信息和文档,还能够查看源码,因为它是开放的。
178+
179+
还是回头到`dir(pprint)`中找一找,有一个`__file__`,它就告诉我们这个模块的位置:
180+
181+
>>> print pprint.__file__
182+
/usr/lib/python2.7/pprint.pyc
183+
184+
我是在ubuntu中为例,读者要注意观察自己的操作系统结果。
185+
186+
虽然是.pyc文件,但是不用担心,根据现实的目录,找到相应的.py文件即可。
187+
188+
$ ls /usr/lib/python2.7/pp*
189+
/usr/lib/python2.7/pprint.py /usr/lib/python2.7/pprint.pyc
190+
191+
果然有一个pprint.py。打开它,就看到源码了。
192+
193+
$ cat /usr/lib/python2.7/pprint.py
194+
195+
...
196+
197+
"""Support to pretty-print lists, tuples, & dictionaries recursively.
198+
199+
Very simple, but useful, especially in debugging data structures.
200+
201+
Classes
202+
-------
203+
204+
PrettyPrinter()
205+
Handle pretty-printing operations onto a stream using a configured
206+
set of formatting parameters.
207+
208+
Functions
209+
---------
210+
211+
pformat()
212+
Format a Python object into a pretty-printed representation.
213+
214+
....
215+
"""
216+
217+
我只查抄了文档中的部分信息,是不是跟前面通过`__doc__`查看的结果一样一样的呢?
218+
219+
请读者在闲暇时间,阅读以下源码。事实证明,这种标准库中的源码是质量最好的。
220+
221+
------
222+
223+
[总目录](./index.md)&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;[上节:编写模块](./218.md)&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;[下节:标准库(2)](./220.md)
224+
225+
如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。

2code/pm.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
#!/usr/bin/env python
22
# coding=utf-8
33

4+
"""
5+
This is a document of the python module.
6+
"""
7+
48
def lang():
59
return "python"
610

index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
##第陆章 模块
8181

8282
1. [编写模块](./219.md)==>模块是程序,模块的位置
83+
2. [标准库(1)](./220.md)==>引用模块的方式,dir()查看属性和方法,模块文档和帮助
8384

8485
标准库和第三方库
8586

0 commit comments

Comments
 (0)