Python提供了一种将定义放入文件中并在脚本或解释器的交互式实例中使用它们的方法。这样的文件称为模块;可以将模块中的定义导入其他模块或主模块中(您可以在顶层和计算器模式下执行的脚本中访问的变量集合)。
导入模块时,说“ hello”,解释器会在包含输入脚本的目录中然后在由环境变量PYTHONPATH指定的目录列表中搜索名为hello.py的文件。
创建一个名为fibonacci.py的文件,并在其中输入以下代码:
def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print()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
现在打开终端,并使用cd命令切换到包含该文件的目录,然后打开Python shell。输入以下语句:
>>> import fibonacci >>> fibonacci.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibonacci.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
您导入了模块并使用了其功能。