一个模块就是一个文件,它里面就是Python代码。一个模块中可以定义函数、类以及变量。一个模块还可以包含 runnable code。
将相关的代码放到一个模块中使得代码更容易理解和使用。当编写一个程序时,不管何时该文件开始变得太大或执行太多不同功能时就要将代码分割进模块中。
1、Laying out a module
模块中元素的通常顺序是:
✦ Docstring and/or general comments (revision log or copyright information,
and so on)
✦ Import statements (see below for more information on importing modules)
✦ Definitions of module-level variables (“constants”)
✦ Definitions of classes and functions
✦ Main function, if any
不要求一定这么做,但它工作得很好并被广泛采用。
注意:人们常常将频繁用到的值放到都是大写字母变量中以便于维护,或者只是更易于阅读。例如:
FTP_PORT = 21 # The standard FTP server control port
这样的一个变量就是“约定中的常量”——Python不会禁止修改它,但调用者不应当修改它的值。
2、Taking inventory of a module
函数 dir(module) 定义在module中的变量、函数,以及类的一个列表。如果不带参数,dir 返回所有当前定义的名字的一个列表。dir(__builtin__) 返回所有built-in names 的一个列表。例如:
>>> dir() # Just after starting Python
[‘__builtins__’, ‘__doc__’, ‘__name__’]
>>> import sys
>>> dir()
[‘__builtins__’, ‘__doc__’, ‘__name__’, ‘sys’]
你可以向 dir 传任何对象(或类),此时得到的是类成员列表。