【python】标准库(第一讲)

简介: 在 Python 被安装的时候,就有不少模块也随着安装到本地的计算机上了。这些东西就如同“能源”、“电力”一样,让 Python 拥有了无限生机,能够非常轻而易举地免费使用很多模块。所以,称之为“自带电池”。它们被称为“标准库”。...

🍁作者简介:🏅云计算领域优质创作者🏅新星计划第三季python赛道TOP1🏅 阿里云ACE认证高级工程师🏅

✒️个人主页:小鹏linux

💊个人社区:小鹏linux(个人社区)欢迎您的加入!

目录

1. 引用的方式

2. 深入探究

3. 帮助、文档和源码

👑👑👑结束语👑👑👑


“Python 自带‘电池’”,听说过这种说法吗?

在 Python 被安装的时候,就有不少模块也随着安装到本地的计算机上了。这些东西就如同“能源”、“电力”一样,让 Python 拥有了无限生机,能够非常轻而易举地免费使用很多模块。所以,称之为“自带电池”。它们被称为“标准库”。

熟悉标准库,是进行编程的必须。

1. 引用的方式

不仅使标准库的模块,所有模块都服从下述引用方式。

最基本的、也是最常用的,还是可读性非常好的:

import modulename

image.gif

例如:

>>> 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'}

image.gif

在对模块进行说明的过程中,我以标准库 pprint 为例。以 pprint.pprint() 的方式应用了一种方法,这种方法能

够让 dict 格式化输出。看看结果,是不是比原来更容易阅读了你?

在 import 后面,理论上可以跟好多模块名称。但是在实践中,我还是建议大家一次一个名称吧。这样简单明

了,容易阅读。

这是用 import pprint 样式引入模块,并以 . 点号的形式引用其方法。

还可以:

>>> from pprint import pprint

image.gif

意思是从 pprint 模块中之将 pprint() 引入,然后就可以这样来应用它:

>>> pprint(a)
{'book': 'www.itdiffer.com',
    'goal': 'from beginner to master',
    'lang': 'Python',
    'teacher': 'qiwsir'}

image.gif

再懒惰一些,可以:

>>> from pprint import *

image.gif

这就将 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'}

image.gif

当然,还可以这样:

>>> from pprint import pprint as pt
>>> pt(a)
{'book': 'www.itdiffer.com',
    'goal': 'from beginner to master',
    'lang': 'python',
    'teacher': 'qiwsir'}

image.gif

但是不管怎么样,一定要让人看懂,过了若干时间,自己也还能看懂。记住:“软件很多时候是给人看的,只是偶尔让机器执行”。

2. 深入探究

继续以 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']

image.gif

对 dir() 并不陌生。从结果中可以看到 pprint 的属性和方法。其中有不少是双划线、电话线开头的。为了不影响我们的视觉,先把它们去掉。

>>> [ m for m in dir(pprint) if not m.startswith('_') ]
['PrettyPrinter', 'isreadable', 'isrecursive', 'pformat', 'pprint', 'saferepr', 'warnings']

image.gif

对这几个,为了能够搞清楚它们的含义,可以使用 help() ,比如:

>>> help(isreadable)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
NameError: name 'isreadable' is not defined

image.gif

这样做是错误的。知道错在何处吗?

>>> help(pprint.isreadable)

image.gif

别忘记了,我前面是用 import pprint 方式引入模块的。

Help on function isreadable in module pprint:
isreadable(object)
    Determine if saferepr(object) is readable by eval().

image.gif

通过帮助信息,能够查看到该方法的详细说明。可以用这种方法一个一个地查过来,反正也不多,对每个方法都熟悉一些。

注意的是 pprint.PrettyPrinter 是一个类,后面的是函数(方法)。

在回头看看 dir(pprint) 的结果,关注一个:

>>> pprint.__all__
['pprint', 'pformat', 'isreadable', 'isrecursive', 'saferepr', 'PrettyPrinter']

image.gif

这个结果是不是眼熟?除了"warnings",跟前面通过列表解析式得到的结果一样。

其实,当我们使用 from pprint import * 的时候,就是将 __all__ 里面的方法引入,如果没有这个,就会将其它

所有属性、方法等引入,包括那些以双划线或者单划线开头的变量、函数,这些东西事实上很少被在引入模块时使用。

3. 帮助、文档和源码

不知道大家是否能够记住看过的上述内容?反正我记不住。所以,我非常喜欢使用 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.

image.gif

pprint.__doc__ 是查看整个类的文档.

还是使用 pm.py 那个文件,增加如下内容:

#!/usr/bin/env Python
# coding=utf-8
"""             #增加的
This is a document of the python module. #增加的
"""             #增加的
def lang():
    ...         #省略了,后面的也省略了

image.gif

在这个文件的开始部分,所有类和方法、以及 import 之前,写一个用三个引号包括的字符串。那就是文档。

>>> import sys
>>> sys.path.append("~/Documents/VBS/StarterLearningPython/2code")
>>> import pm
>>> print pm.__doc__
This is a document of the python module.

image.gif

这就是撰写模块文档的方法,即在 .py 文件的最开始写相应的内容。这个要求应该成为开发习惯。

Python 的模块,不仅可以看帮助信息和文档,还能够查看源码,因为它是开放的。

还是回头到 dir(pprint) 中找一找,有一个 __file__ ,它就告诉我们这个模块的位置:

>>> print pprint.__file__
/usr/lib/python2.7/pprint.pyc

image.gif

我是在 ubuntu 中为例,读者要注意观察自己的操作系统结果。

虽然是 .pyc 文件,但是不用担心,根据现实的目录,找到相应的 .py 文件即可

$ ls /usr/lib/python2.7/pp*
/usr/lib/python2.7/pprint.py /usr/lib/python2.7/pprint.pyc

image.gif

果然有一个 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.
....
"""

image.gif

事实证明,这种标准库中的源码是质量最好的!

👑👑👑结束语👑👑👑

image.gif

目录
相关文章
|
21小时前
|
机器学习/深度学习 算法 数据挖掘
机器学习--K近邻算法,以及python中通过Scikit-learn库实现K近邻算法API使用技巧
机器学习--K近邻算法,以及python中通过Scikit-learn库实现K近邻算法API使用技巧
|
1天前
|
Python
使用Seaborn库创建图形的使用案例
【4月更文挑战第29天】该代码段首先导入seaborn和matplotlib库,然后加载名为&quot;titanic&quot;的数据集。接着,它创建一个画布并设定子图大小。通过seaborn的FacetGrid以&quot;Attrition_Flag&quot;为列进行分组,映射数据到网格上,用histplot展示&quot;Customer_Age&quot;的直方图分布。同样,也使用boxplot方法生成&quot;Freq&quot;的箱线图。最后展示所有图形。
8 2
|
4天前
|
数据可视化 数据挖掘 数据处理
statsmodels, Python 统计分析工具库!
statsmodels, Python 统计分析工具库!
19 1
|
4天前
|
机器学习/深度学习 数据挖掘 API
pymc,一个灵活的的 Python 概率编程库!
pymc,一个灵活的的 Python 概率编程库!
10 1
|
4天前
|
JSON 人工智能 算法
pyjwt,一个强大的 Python JWT解析校验库!
pyjwt,一个强大的 Python JWT解析校验库!
12 0
|
4天前
|
人工智能 编解码 数据可视化
moviepy,一个超酷的 Python 视频处理库!
moviepy,一个超酷的 Python 视频处理库!
7 0
|
4天前
|
机器学习/深度学习 人工智能 物联网
hummingbird,一个便于将模型部署到边缘设备的Python库!
hummingbird,一个便于将模型部署到边缘设备的Python库!
14 1
|
4天前
|
机器学习/深度学习 人工智能 物联网
hummingbird,一个非常好用的 Python 库!
hummingbird,一个非常好用的 Python 库!
18 1
|
4天前
|
关系型数据库 数据库连接 数据库
asqlcell,一个超强的 Python 库!
asqlcell,一个超强的 Python 库!
18 7
|
4天前
|
测试技术 开发者 Python
pyautogui,一个超酷的 Python 库!
pyautogui,一个超酷的 Python 库!
16 4