15.4 如何创建模块

下面来创建模块。模块就是一个 Python 文件,类似代码清单 15-1 中给出的文件。在一个 IDLE 编辑器窗口中键入代码清单 15-1 中的代码,把它保存为 my_module.py。

代码清单 15-1 创建一个模块

  1. # this is the file "my_module.py"
  2. # we're going to use it in another program
  3. def c_to_f(celsius):
  4. fahrenheit = celsius * 9.0 / 5 + 32
  5. return fahrenheit

就这么简单!这样就创建了一个模块!模块中只有一个函数,也就是 c_to_f() 函数,它会把温度从摄氏度转换为华氏度。

接下来我们在另一个程序中使用 my_module.py。