17.8 타입 기반 디스패치
앞 절에서 두 Time 객체끼리 더했지만, Time 객체에 정수를 더하는 게 필요할 수도 있다. 아래에 나오는 _ _add_ _ 버전은 other의 타입을 검사하고 add_time 또는 increment 중에 하나를 호출한다.
# class 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 int_to_time(seconds)
def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)