现在 Time 对象有了自己的加法方法,就可以与 sum 函数来配合使用了:
$ cat c.py
#!/bin/python
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
def int_to_time(self, seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def __add__(self, other):
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)
def add_time(self, other):
seconds = self.time_to_int() + other.time_to_int()
return self.int_to_time(seconds)
def increment(self, seconds):
seconds += self.time_to_int()
return self.int_to_time(seconds)
def __radd__(self, other):
return self.__add__(other)
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c]+1
return d
t1 = Time(3, 30)
t2 = Time(3, 31)
t3 = Time(3, 32)
total = sum([t1, t2, t3])
print(total)
$ python3 c.py
10:33:00
总的来说,如果一个函数内的所有运算都可以处理某一类型,这个函数就适用于这一类型了。