A side effect of this question is that I was lead to this post, which states:
Whenever isinstance is used, control flow forks; one type of object goes dow
To elaborate further on the comment I made under Justin's answer, I would keep his code for __iadd__
(i.e., so MyTime objects can only be added to other MyTime objects) and rewrite __init__
in this way:
def __init__(self, **params):
if params.get('sec'):
t = params['sec']
self.h = t/3600
t %= 3600
self.m = t/60
t %= 60
self.s = t
elif params.get('time'):
t = params['time']
self.h = t.h
self.m = t.m
self.s = t.s
else:
if params:
raise TypeError("__init__() got unexpected keyword argument '%s'" % params.keys()[0])
else:
raise TypeError("__init__() expected keyword argument 'sec' or 'time'")
# example usage
t1 = MyTime(sec=30)
t2 = MyTime(sec=60)
t2 += t1
t3 = MyTime(time=t1)
I just tried to pick short keyword arguments, but you may want to get more descriptive than I did.