魔术方法的简单定制

魔术方法的简单定制学习笔记

简单例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import time as t

class MyTimer():
def __init__(self):
self.unit = ['Year ','Month ','Day ','Hour ','Minute ','Second']
self.prompt = "hasn't started,use start() first"
self.lasted = []
self.begin = 0
self.end = 0

def __str__(self):
return self.prompt
__repr__ = __str__

def __add__(self,other):
prompt = "Both lasted :"
result = []
for index in range(6):
result.append(self.lasted[index] + other.lasted[index])
if result[index]:
prompt += (str(result[index]) + self.unit[index])
return prompt

#start timing
def start(self):
self.begin = t.localtime()
self.prompt = "Use the stop() to stop"
print("start...")

#stop timing
def stop(self):
if not self.begin:
print('Use start() first')
else:
self.end = t.localtime()
self._calc()
print("stoped!")

#count time
def _calc(self):
self.lasted = []
self.prompt = "All lasted :"
for index in range(6):
self.lasted.append(self.end[index] - self.begin[index])
self.prompt += (str(self.lasted[index]) + self.unit[index])

#init for next turn
self.begin = 0
self.end = 0



```
运行结果:

t1 = MyTimer()
t1.start()
start…
t1.stop()
stoped!
t1
All lasted :0Year 0Month 0Day 0Hour 0Minute 8Second
t2 = MyTimer()
t2
hasn’t started,use start() first
t2.stop()
Use start() first
t2.start()
start…
t2.stop()
stoped!
t1 + t2
‘Both lasted :16Second’

`