新版教材12章案例171页问题
import time as tclass MyTimer:
#开始计时
def start(self):
self.begin = t.localtime()
print("计时开始...")
#停止计时
def stop(self):
self.end = t.localtime()
self._calc()
print("计时结束...")
#内部方法计算运行时间
def _calc(self):
self.lasted = []
self.prompt="总共运行了"
for index in range(6):
self.lasted.append(self.end - self.begin)
self.prompt +=str(self.lasted)
print(self.prompt)
def __str__(self):
return self.prompt
__repr__ = __str__
def __init__(self):
self.prompt = "未开始计时"
self.lasted = []
self.begin = 0
self.end = 0
def __int__(self):
self.unit = ["年","月","天","时","分","秒"]
self.prompt = "未开始计时"
self.lasted =[]
self.begin = 0
self.end = 0
#计算运行时间
def _calc(self):
self.lasted = []
self.prompt = "总共运行了"
for index in range(6):
self.lasted.append(self.end - self.begin)
if self.lasted:
self.prompt +=(str(self.lasted)+ self.unit)
运行报错:
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
t1.stop()
File "/Users/liuke/Desktop/p12_1.py", line 11, in stop
self._calc()
File "/Users/liuke/Desktop/p12_1.py", line 48, in _calc
self.prompt +=(str(self.lasted)+ self.unit)
AttributeError: 'MyTimer' object has no attribute 'unit def __init__()
你输入错误,初始化失败。 import time as t
class MyTimer:
def __init__(self):
self.unit = ['年', '月', '天', '小时', '分钟', '秒']
self.prompt = "未开始计时!"
self.lasted = []
self.begin = 0
self.end = 0
def __str__(self):
return self.prompt
__repr__ = __str__
# 开始计时
def start(self):
self.begin = t.localtime()
self.prompt = "提示:请先调用 stop() 停止计时!"
print("计时开始...")
# 停止计时
def stop(self):
if not self.begin:
print("提示:请先调用 start() 进行计时!")
else:
self.end = t.localtime()
self._calc()
print("计时结束!")
# 内部方法,计算运行时间
def _calc(self):
self.lasted = []
self.prompt = "总共运行了"
for index in range(6):
self.lasted.append(self.end - self.begin)
if self.lasted:
self.prompt +=(str(self.lasted)+ self.unit)
页:
[1]