Let's say your class looks like this:
class mytime(object):
def __init__(self, h, m):
self.h = h
self.m = m
def __add__(self, other):
return mytime(self.h + other.h, self.m + other.m)
def __repr__(self):
return '%i:%i' % (self.h, self.m)
and you use it like this:
a = mytime(10, 10)
b = mytime(2, 22)
print a + b
and it will work as expect:
12:32
Problem:
What you want to do is:
l = [a, b]
print sum(l)
but it will fail:
TypeError: unsupported operand type(s) for +: 'int' and 'mytime'
The problem is that the sum
function will start with 0
and will add up all values of the list. It will try to evaluate
0 + mytime(10, 10)
which will fail.
Solution:
The solution to your problem is implementing the __radd__
function, which represents "reverse add" and is called when the arguments can't be resolved in the "forward" direction. For example, x + y
is evaluated as x.__add__(y)
if possible, but if that doesn't exist then Python tries y.__radd__(x)
.
So you can add the following method to your class:
def __radd__(self, other):
return mytime(self.h, self.m)
and the sum
function will work for you (in this implementation ignoring the other
value, which is probably fine in your case).