51学通信论坛2017新版

标题: 实例展示函数如何提高代码的效率和简洁易懂 [打印本页]

作者: admin    时间: 2017-12-29 23:40
标题: 实例展示函数如何提高代码的效率和简洁易懂
启用函数的代码:
  1. def print_models(unprinted_designs,completed_models):
  2.     while unprinted_designs:
  3.         current_design = unprinted_designs.pop()
  4.         print("printing model:"+current_design)
  5.         completed_models.append(current_design)
  6. def show_completed_models(completed_models):
  7.     print("\nthe following models have been printed:")
  8.     for completed_model in completed_models:
  9.         print(completed_model)
  10. unprinted_designs = ['iphone case','robot pendant','dodecahedron']
  11. completed_models=[]
  12. print_models(unprinted_designs,completed_models)
  13. show_completed_models(completed_models)
复制代码
不启用函数的代码:
  1. unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
  2. completed_models = []
  3. while unprinted_designs:
  4.     current_design = unprinted_designs.pop()
  5.     print("Printing model: " + current_design)
  6.     completed_models.append(current_design)
  7. print("\nThe following models have been printed:")
  8. for completed_model in completed_models:
  9.     print(completed_model)
复制代码
以上两段代码的功能和输出结果是完全一样的,如下:
  1. Printing model: dodecahedron
  2. Printing model: robot pendant
  3. Printing model: iphone case
  4. The following models have been printed:
  5. dodecahedron
  6. robot pendant
  7. iphone case
复制代码
由此可以看出,启用了函数以后的代码更有序,更有效率。两个函数各司其职。




作者: admin    时间: 2017-12-29 23:43
   我们创建了一个未打印的设计列表,还创建了一个空列表,用于存储打印好的模型。接下来,由于我们已经定义了两个函数,因此只需调用它们并传入正确的实参即可。我们调用print_models()并向它传递两个列表;像预期的一样, print_models()模拟打印设计的过程。接下来,我们调用show_completed_models(),并将打印好的模型列表传递给它,让其能够指出打印了哪些模型。描述性的函数名让别人阅读这些代码时也能明白,虽然其中没有任何注释。
   相比于没有使用函数的版本,这个程序更容易扩展和维护。如果以后需要打印其他设计,只需再次调用print_models()即可。如果我们发现需要对打印代码进行修改,只需修改这些代码一次,就能影响所有调用该函数的地方;与必须分别修改程序的多个地方相比,这种修改的效率更高。
   这个程序还演示了这样一种理念,即每个函数都应只负责一项具体的工作。第一个函数打印每个设计,而第二个显示打印好的模型;这优于使用一个函数来完成两项工作。编写函数时,如果你发现它执行的任务太多,请尝试将这些代码划分到两个函数中。别忘了,总是可以在一个函数中调用另一个函数,这有助于将复杂的任务划分成一系列的步骤。  





欢迎光临 51学通信论坛2017新版 (http://bbs.51xuetongxin.com/) Powered by Discuz! X3