Python44讲课后题进阶版时间
import time as t
class Time():
def __init__(self):
self.unit = ['年','月','日','时','分','秒']
self.prompt = "未开始计时!"
self.lasted = []
self.begin = 0
self.end = 0
self.borrow =
def __str__(self):
return self.prompt
__repr__ = __str__
#时间相加计算
def __add__(self,other):
prompt = '总共运行了'
result = []
for i in range(6):
result.append(self.lasted + other.lasted)
if result:
prompt += (str(result) + self.unit)
return prompt
#开始计时
def start(self):
self.begin = t.localtime()
self.prompt = '提示:请先调用stop()停止计时!'
print('计时开始……')
prompt = '开始时间为:'
for i in range(6):
if self.begin:
prompt += (str(self.begin) + self.unit)
#时间借位时,借位列表
temp = self.begin
if (temp == 1) or (temp == 3) or (temp == 5) or(temp == 7) or (temp == 8) or (temp == 10) or(temp == 12):
self.borrow = 31
else:
if (temp == 2):
self.borrow = 29
else:
self.borrow = 30
return prompt
#停止计时
def stop(self):
if not self.begin:
print('提示;请先调用start()进行计时')
else:
self.end = t.localtime()
self._cale()
prompt = '结束时间为:'
for i in range(6):
if self.end:
prompt += (str(self.end) + self.unit)
self._initialize()
print('计时结束!')
return prompt
#计算运行时间
def _cale(self):
self.lasted = []
self.prompt = "总共运行了"
for i in range(6):
self.lasted.append(self.end - self.begin)
#借位操作,计算时间
for i in :
temp = self.lasted
if temp <0:
j = 1
while self.lasted <1:
self.lasted += self.borrow-1
self.lasted -= 1
j += 1
self.lasted += self.borrow
self.lasted -= 1
for i in range(6):
if self.lasted:
self.prompt += (str(self.lasted) + self.unit)
#为下一轮计时初始化
def _initialize(self):
self.begin = 0
self.end = 0
页:
[1]