## 2016年10月20日木曜日

### Python - Classes and Methods(attributes)

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 17.(Classes and Methods)のExercises 17-1.(No. 3929)を取り組んでみる。

Exercises 17-1.(No. 3929)

コード(Emacs)

```#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Time:

def __init__(self, hour=0, minute=0, second=0):
self.seconds = hour * 60 * 60 + minute * 60 + second

def __str__(self):
minute, second = divmod(self.seconds, 60)
hour, minute = divmod(minute, 60)
return '%.2d:%.2d:%.2d' % (hour, minute, second)

def print_time(self):
print(str(self))

def time_to_int(self):
return self.seconds

def is_after(self, other):
return self.time_to_int() > other.time_to_int()

if isinstance(other, Time):
else:
return self.increment(other)

assert self.is_valid() and other.is_valid()
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)

def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)

def is_valid(self):
return 0 <= self.seconds < 24 * 60 * 60

def int_to_time(seconds):
time = Time(0, 0, seconds)
return time

def main():
start = Time(9, 45, 00)
start.print_time()

end = start.increment(1337)
#end = start.increment(1337, 460)
end.print_time()

print('Is end after start?')
print(end.is_after(start))

print('Using __str__')
print(start, end)

start = Time(9, 45)
duration = Time(1, 35)
print(start + duration)
print(start + 1337)
print(1337 + start)

print('Example of polymorphism')
t1 = Time(7, 43)
t2 = Time(7, 41)
t3 = Time(7, 37)
total = sum([t1, t2, t3])
print(total)

if __name__ == '__main__':
main()
```

```\$ ./Time2.py
09:45:00
10:07:17
Is end after start?
True
Using __str__
09:45:00 10:07:17
11:20:00
10:07:17
10:07:17
Example of polymorphism
23:01:00
\$
```