Python强大的自有模块——标准库

管理员账号

2017-03-31

小编说: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查看的结果一样呢?

请读者在闲暇时间阅读源码。事实证明,这种标准库中的源码是质量最好的。阅读高质量的代码是提高编程水平的途径之一。

读者评论

相关博文

  • 标准库举例:sys、copy

    标准库举例:sys、copy

    管理员账号 2017-04-07

    小编说:Python标准库内容非常多,有人专门为此写过一本书。本文将选择几个呈现出来,一来显示标准库之强大功能,二来演示如何理解和使用标准库。sys是常用的标准库,已经不陌生了;copy也是已经用过的标准库。先从熟悉的入手,容易理解,...

    管理员账号 2017-04-07
    381 0 0 0