| 
                         以下是一个测试测试用户正确感知时间流逝能力的新程序: 
- #!/usr/bin/env python3 
 - from mymodularity import timestamp 
 - print("Press the RETURN key. Count to 3, and press RETURN again.") 
 - input() 
 - timestamp.Timer("Started timer at ") 
 - print("Count to 3...") 
 - input() 
 - timestamp.Timer("You slept until ") 
 
  
将你的新程序保存为 response.py,运行它: 
- $ python3 ./response.py 
 - Press the RETURN key. Count to 3, and press RETURN again. 
 - Started timer at 1560714482.3772075 
 - Count to 3... 
 - You slept until 1560714484.1628013 
 
  
函数和所需参数 
新版本的 timestamp 模块现在 需要 一个 msg 参数。这很重要,因为你的第一个应用程序将无法运行,因为它没有将字符串传递给  timestamp.Timer 函数: 
- $ python3 ./sleeptest.py 
 - Testing Python sleep()... 
 - Traceback (most recent call last): 
 -  File "./sleeptest.py", line 8, in <module> 
 -  timestamp.Timer() 
 - TypeError: Timer() missing 1 required positional argument: 'msg' 
 
  
你能修复你的 sleeptest.py 应用程序,以便它能够与更新后的模块一起正确运行吗? 
变量和函数 
通过设计,函数限制了变量的范围。换句话说,如果在函数内创建一个变量,那么这个变量 只  在这个函数内起作用。如果你尝试在函数外部使用函数内部出现的变量,就会发生错误。 
下面是对 response.py 应用程序的修改,尝试从 timestamp.Timer() 函数外部打印 msg 变量: 
- #!/usr/bin/env python3 
 - from mymodularity import timestamp 
 - print("Press the RETURN key. Count to 3, and press RETURN again.") 
 - input() 
 - timestamp.Timer("Started timer at ") 
 - print("Count to 3...") 
 - input() 
 - timestamp.Timer("You slept for ") 
 - print(msg) 
 
  
试着运行它,查看错误: 
- $ python3 ./response.py 
 - Press the RETURN key. Count to 3, and press RETURN again. 
 - Started timer at 1560719527.7862902 
 - Count to 3... 
 - You slept for 1560719528.135406 
 - Traceback (most recent call last): 
 -  File "./response.py", line 15, in <module> 
 -  print(msg) 
 - NameError: name 'msg' is not defined 
 
  
应用程序返回一个 NameError 消息,因为没有定义 msg。这看起来令人困惑,因为你编写的代码定义了 msg,但你对代码的了解比 Python  更深入。调用函数的代码,不管函数是出现在同一个文件中,还是打包为模块,都不知道函数内部发生了什么。一个函数独立地执行它的计算,并返回你想要它返回的内容。这其中所涉及的任何变量都只是  本地的:它们只存在于函数中,并且只存在于函数完成其目的所需时间内。 
Return 语句 
如果你的应用程序需要函数中特定包含的信息,那么使用 return 语句让函数在运行后返回有意义的数据。 
时间就是金钱,所以修改 timestamp 函数,以使其用于一个虚构的收费系统: 
- #!/usr/bin/env python3 
 - import time 
 - def Timer(msg): 
 -  print(str(msg) + str(time.time() ) ) 
 -  charge = .02 
 -  return charge 
 
  
现在,timestamp 模块每次调用都收费 2 美分,但最重要的是,它返回每次调用时所收取的金额。 
以下一个如何使用 return 语句的演示: 
- #!/usr/bin/env python3 
 - from mymodularity import timestamp 
 - print("Press RETURN for the time (costs 2 cents).") 
 - print("Press Q RETURN to quit.") 
 - total = 0 
 - while True: 
 -  kbd = input() 
 -  if kbd.lower() == "q": 
 -  print("You owe $" + str(total) ) 
 -  exit() 
 -  else: 
 -  charge = timestamp.Timer("Time is ") 
 -  total = total+charge 
 
                          (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |