加入收藏 | 设为首页 | 会员中心 | 我要投稿 西安站长网 (https://www.029zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

使用 Python 函数进行模块化

发布时间:2019-09-03 08:55:11 所属栏目:建站 来源:Seth Kenlon
导读:副标题#e# 你是否对函数、类、方法、库和模块等花哨的编程术语感到困惑?你是否在与变量作用域斗争?无论你是自学成才的还是经过正式培训的程序员,代码的模块化都会令人困惑。但是类和库鼓励模块化代码,因为模块化代码意味着只需构建一个多用途代码块集合,

以下是一个测试测试用户正确感知时间流逝能力的新程序:

  1. #!/usr/bin/env python3 
  2. from mymodularity import timestamp 
  3. print("Press the RETURN key. Count to 3, and press RETURN again.") 
  4. input() 
  5. timestamp.Timer("Started timer at ") 
  6. print("Count to 3...") 
  7. input() 
  8. timestamp.Timer("You slept until ") 

将你的新程序保存为 response.py,运行它:

  1. $ python3 ./response.py 
  2. Press the RETURN key. Count to 3, and press RETURN again. 
  3. Started timer at 1560714482.3772075 
  4. Count to 3... 
  5. You slept until 1560714484.1628013 

函数和所需参数

新版本的 timestamp 模块现在 需要 一个 msg 参数。这很重要,因为你的第一个应用程序将无法运行,因为它没有将字符串传递给 timestamp.Timer 函数:

  1. $ python3 ./sleeptest.py 
  2. Testing Python sleep()... 
  3. Traceback (most recent call last): 
  4.  File "./sleeptest.py", line 8, in <module> 
  5.  timestamp.Timer() 
  6. TypeError: Timer() missing 1 required positional argument: 'msg' 

你能修复你的 sleeptest.py 应用程序,以便它能够与更新后的模块一起正确运行吗?

变量和函数

通过设计,函数限制了变量的范围。换句话说,如果在函数内创建一个变量,那么这个变量 只 在这个函数内起作用。如果你尝试在函数外部使用函数内部出现的变量,就会发生错误。

下面是对 response.py 应用程序的修改,尝试从 timestamp.Timer() 函数外部打印 msg 变量:

  1. #!/usr/bin/env python3 
  2. from mymodularity import timestamp 
  3. print("Press the RETURN key. Count to 3, and press RETURN again.") 
  4. input() 
  5. timestamp.Timer("Started timer at ") 
  6. print("Count to 3...") 
  7. input() 
  8. timestamp.Timer("You slept for ") 
  9. print(msg) 

试着运行它,查看错误:

  1. $ python3 ./response.py 
  2. Press the RETURN key. Count to 3, and press RETURN again. 
  3. Started timer at 1560719527.7862902 
  4. Count to 3... 
  5. You slept for 1560719528.135406 
  6. Traceback (most recent call last): 
  7.  File "./response.py", line 15, in <module> 
  8.  print(msg) 
  9. NameError: name 'msg' is not defined 

(编辑:西安站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读