A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module is imported somewhere.6.1
模块可以像函数定义一样包含执行语句。这些语句通常用于初始化模块。它们只在模块第一次导入时执行一次。6.2
Each module has its own private symbol table, which is used as the
global symbol table by all functions defined in the module.
Thus, the author of a module can use global variables in the module
without worrying about accidental clashes with a user's global
variables.
On the other hand, if you know what you are doing you can touch a
module's global variables with the same notation used to refer to its
functions,
modname.itemname
.
对应于定义模块中所有函数的全局语义表,每一个模块有自己的私有语义表。因此,模块作者可以在模块中使用一些全局变量,不会因为与用户的全局变量冲突而引发错误。
另一方面,如果你确定你需要这个,可以像引用模块中的函数一样获取模块中的全局变量,形如:modname.itemname
。
Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module's global symbol table.
模块可以导入(import)其它模块。习惯上所有的 import语句都放在模块(或脚本,等等)的开头,但这并不是必须的。被导入的模块名入在本模块的全局语义表中。
There is a variant of the import statement that imports names from a module directly into the importing module's symbol table. For example:
import 语句的一个变体直接从被导入的模块中导入命名到本模块的语义表中。例如:
>>> from fibo import fib, fib2 >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken
in the local symbol table (so in the example, fibo
is not
defined).
这样不会从局域语义表中导入模块名(如上所示, fibo
没有定义)。
There is even a variant to import all names that a module defines:
这里还有一个变体从模块定义中导入所有命名:
>>> from fibo import * >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore
(_
).
这样可以导入所有除了以下划线(_
)开头的命名。