classMyTimer(): # rewrite the __init__ def__init__(self): self.unit = ['year', 'month', 'day', 'hour', 'minute', 'second'] self.prompt = "Timer has not started." self.lasted = [] # avoid the attribute the same name with method self.begin = 0 self.end = 0
# rewrite the magic methods def__str__(self): returnself.prompt
__repr__ = __str__
# realize the add def__add__(self, other): prompt = "The all runtime is " result = [] for index in range(6): result.append(self.lasted[index] + other.lasted[index]) if result[index]: prompt += (str(result[index]) + self.unit[index])
# start timer defstart(self): self.begin = t.localtime() self.prompt = "Pls call the stop first!" print("Timer is on.")
# stop timer defstop(self): ifnotself.begin: print("Pls call the start first") else: self.end = t.localtime() self._calc() print("Timer is off.")
# calculate the runtime, method inside(started with ). def_calc(self): self.lasted = [] self.prompt = "Runtime of timer is " for index in range(6): self.lasted.append(self.end[index] - self.begin[index]) ifself.lasted[index]: self.prompt += (str(self.lasted[index]) + self.unit[index])
# Initialize again self.begin = 0 self.end = 0
Result:
1 2 3 4 5 6 7 8 9 10 11 12 13
>>>t1 = MyTimer() >>>t1 Timer has not started. >>>t1.start() Timer is on. >>>t1 Pls call the stop first! >>>t1.stop() Timer is off. >>>t1 Runtime of timer is 6second >>>print(t1) Runtime of timer is 6second
Advanced Customization
The code before have some problem.
The precision of timer is second. We can use the other bank to be advanced.