编程原来是这样程序员首页投稿(暂停使用,暂停投稿)

编程入门03:Python模块与库

2018-02-28  本文已影响123人  starglow_leo

上一篇:编程入门02:Python基础语法

现在我们已经用过id()、input()、print()等多个函数,这些都是默认可用的对象。Python官方还提供了更多的可重用对象,它们分门别类地放在不同的“模块”(Module)之中,你可以在需要的时候“引入”(Import)特定的模块。引入模块之后,默认的主“名称空间”(Namespace)中就会增加指向模块对象的变量,可以使用“模块变量.成员变量”的形式对模块中的对象进行“引用”(Reference)——“.”称为引用运算符,可以读作“的”。

现在我们尝试引入数学模块math,以使用其中的数学工具:

>>> dir()  # dir函数查看主名称空间中的变量列表,默认已存在7个变量
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> import math  # 引入math模块,也可以同时引入多个模块(用逗号分隔)
>>> dir()  # 主名称空间中增加了math变量
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math']
>>> math  # math变量指向math模块
<module 'math' (built-in)>
>>> math.sqrt(4)  # 平方根函数
2.0
>>> math.exp(2)  # 自然常数幂函数
7.38905609893065
>>> math.pi  # 圆周率常数
3.141592653589793
>>> math.e  # 自然常数
2.718281828459045
>>> dir(math)  # dir函数查看math模块的成员
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

每个模块都拥有自己的名称空间,这样变量名只需在本名称空间中不重复即可。用模块名称作为dir函数的参数,就可以查看模块名称空间中的变量列表。如果想要知道每个函数如何使用,则可以使用help函数:

>>> help(math.exp)
Help on built-in function exp in module math:

exp(...)
    exp(x)
    
    Return e raised to the power of x.

接下来尝试引入用于子进程管理的模块subprocess,这次增加了as关键词,可以指定变量名称而不使用默认名称:

>>> import subprocess as sp  # 引入subprocess模块,自定义变量名sp(模块名太长引用起来不方便)
>>> sp.call("cmd")  # call函数调用命令提示符程序cmd.exe(可以调用任何可执行程序)
03_sp.png

再来尝试用于生成随机数的模块random,这次再换一种写法——直接将其中的某个变量引入主名称空间(也可以同时引入用逗号分隔的多个变量):

>>> from random import randint  # 从random模块引入randint方法
>>> help(randint)  # 查看randint的说明:随机返回指定开区间内的整数
Help on method randint in module random:

randint(a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

>>> randint(1,6)  # 随机生成1到6之间的整数,即模拟掷骰子
5
>>> randint(1,6)
2

这样引入的变量就能象input、print那样直接使用了,如果写成“from random import *”则会将模块中的所有成员引入主名称空间,不过实际编程中不建议这样做。

模块的集合被称为“库”(Library),Python官方提供的所有模块共同组成了庞大的“Python标准库”。在IDLE主菜单中点击 Help > Python Docs > The Python Standard Library 查看Python标准库的详细说明,官网也提供了在线版本 https://docs.python.org/3/library/index.html 你可以先通读该页面建立起对Python标准库的大致印象,今后有需要时就能知道可以引入什么模块,再用dir函数配合help函数查看具体用法。

你可能注意到了主名称空间默认存在的7个变量中有一个“__builtins__”,它指向一个名为builtins的模块,只要你dir一下就会找到input、print等等熟悉的名字——这些函数之所以默认可用,就是因为Python解释器自动引入了builtins这个模块:

>>> __builtins__
<module 'builtins' (built-in)>
>>> import builtins
>>> id(__builtins__)
2723238745656
>>> id(builtins)
2723238745656

——编程原来是这样……

编程小提示:Python之禅

Python标准库中有一个小彩蛋,只要你引入this这个模块,就能看到一段“Python之禅”,这是一位Python核心开发者对于程序设计的心得感悟,文笔饶有趣味,让我们在学习Python的过程中慢慢体会其中蕴含的丰富哲理吧……

>>> import this
The Zen of Python, by Tim Peters
蟒宗之禅语,提姆彼得斯(中文是我加的,参考了几种网上的译文)

Beautiful is better than ugly.
优美胜于丑陋
Explicit is better than implicit.
明白胜于晦暗
Simple is better than complex.
简洁胜于繁复
Complex is better than complicated.
繁复胜于艰深
Flat is better than nested.
扁平胜于嵌套
Sparse is better than dense.
松散胜于聚集
Readability counts.
代码确保易读
Special cases aren't special enough to break the rules.
规则拒绝特例
Although practicality beats purity.
实用不求纯净
Errors should never pass silently.
错误不可放过
Unless explicitly silenced.
除非明确理由
In the face of ambiguity, refuse the temptation to guess.
模棱两可之间,不要随意猜测
There should be one-- and preferably only one --obvious way to do it.
必有唯一选择,明显胜过其余
Although that way may not be obvious at first unless you're Dutch.
起初无法分辨,只因你非大神
Now is better than never.
尝试好过放弃
Although never is often better than *right* now.
但须谋定而动
If the implementation is hard to explain, it's a bad idea.
实现难以解释,定是糟糕方案
If the implementation is easy to explain, it may be a good idea.
实现易于解释,或为良好方案
Namespaces are one honking great idea -- let's do more of those!
名称空间极好,诸君多加使用!

下一篇:编程入门04:Python第三方包

上一篇下一篇

猜你喜欢

热点阅读