Magic Methods 3

Customization

Requirements:

  • Customize a class of timer
  • Function with ‘start’ and ‘stop’ methods
  • t1 and print(t1) -> Result
  • When the timer is stopped or yet not started, call the relevant method for tips.
  • Timer can add together.
  • Limited bank.

Bank

  • localtime in time module
  • time.localtime -> format of struct_time
  • rewrite of __str__ , __repr__

Expanded Reading: time module

Code

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():
# 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):
return self.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
def start(self):
self.begin = t.localtime()
self.prompt = "Pls call the stop first!"
print("Timer is on.")

# stop timer
def stop(self):
if not self.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])
if self.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.
  • The calculation of the timer will be -1.

Code New:

  • To Be Continue

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!