第10章 开箱即用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010819416/article/details/82468997

10.1 模块

10.1.1 模块就是程序

10.1.2 模块是用来下定义的

1 在模块中定义函数

2 在模块中添加代码

10.1.3 让模块可用

1 将模块放在正确的位置

2 告诉解释器到哪里去查找

10.1.4 包

为组织模块,可将其编组为包(package)。包目录必须包含文件__init__.py

10.2 模块

10.2.1 模块包含什么

1 使用dir

>>> import copy
>>> [n for n in dir(copy) if not n.startswith('_')]
['Error', 'copy', 'deepcopy', 'dispatch_table', 'error']

2 变量__all__

>>> copy.__all__
['Error', 'copy', 'deepcopy']

10.2.2 使用help获取帮助

>>> help(copy.copy)
Help on function copy in module copy:

copy(x)
    Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.

>>> 

10.2.3 文档

>>> print(range.__doc__)
range(stop) -> range object
range(start, stop[, step]) -> range object

Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
>>> 

10.2.4 使用源代码

>>> print(copy.__file__)
D:\Program Files\Python\Python37\lib\copy.py
>>> 

10.3 标准库:一些深受欢迎的模块

10.3.1 sys
能够访问与Python解释器紧密相关的变量和函数。

# 反转并打印命令行参数
import sys
args = sys.argv[1:]
args.reverse()
print(' '.join(args))
python aagrv.py a b c
c b a

10.3.2 os
模块os让你能够访问多个操作系统服务。

10.3.3 fileinput

10.3.4 集合、堆和双端队列

1 集合

>>> set(range(10))
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> 

2 堆
模块为heapq.

3 双端队列(及其他集合)
模块collections

10.3.5 time

10.3.6 random
随机数

10.3.7 shelve 和 json

shelve将数据存储到文件中。

10.3.8 re
提供对正则表达式的支持

10.3.9 其他有趣的标准模块

10.4 小结

猜你喜欢

转载自blog.csdn.net/u010819416/article/details/82468997