If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you've written in several programs without copying its definition into each program.
如果你退出Python解释器重新进入,以前创建的一切定义(变量和函数)就全部丢失了。因此,如果你想写一些长久保存的程序,最好使用一个文本编辑器来编写程序,把保存好的文件输入解释器。我们称之为创建一个脚本。程序变得更长一些了,你可能为了方便维护而把它分离成几个文件。你也可能想要在几个程序中都使用一个常用的函数,但是不想把它的定义复制到每一个程序里。
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
为了满足这些需要,Python提供了一个方法可以从文件中获取定义,在脚本或者解释器的一个交互式实例中使用。这样的文件被称为模块;模块中的定义可以导入到另一个模块或主模块中(在脚本执行时可以调用的变量集位于最高级,并且处于计算器模式)
A module is a file containing Python definitions and statements. The
file name is the module name with the suffix .py appended. Within
a module, the module's name (as a string) is available as the value of
the global variable __name__
. For instance, use your favorite text
editor to create a file called fibo.py in the current directory
with the following contents:
模块是包括Python定义和声明的文件。文件名就是模块名加上 .py
后缀。模块的模块名(做为一个字符串)可以由全局变量 __name__
得到。例如,你可以用自己惯用的文件编辑器在当前目录下创建一个叫
fibo.py 的文件,录入如下内容:
# Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
Now enter the Python interpreter and import this module with the following command:
现在进入Python解释器,用如下命令导入这个模块
>>> import fibo
This does not enter the names of the functions defined in fibo
directly in the current symbol table; it only enters the module name
fibo
there.
Using the module name you can access the functions:
这样做不会直接把 fibo
中的函数导入当前的语义表;,它只是引入了模块名 fibo
。你可以通过模块名按如下方式访问这个函数:
>>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] >>> fibo.__name__ 'fibo'
If you intend to use a function often you can assign it to a local name:
如果你想要直接调用函数,通常可以给它赋一个本地名称:
>>> fib = fibo.fib >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377