2016年10月20日木曜日

開発環境

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()

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

    def __radd__(self, other):
        return self.__add__(other)

    def add_time(self, 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()

入出力結果(Terminal, IPython)

$ ./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
$

0 コメント:

コメントを投稿

Comments on Google+: