Define "__sum__" for a class

Is there something like a __sum__ method, similar to __add__, in order to sum up a list of instances of classes into a new class instance?

I need this because in my case sum([a,b,c]) should be different from sum([sum([a,b]), c]). In other words, the sum really depends on an arbitrary number of arguments, and cannot be defined in terms of a binary operation __add__.


Summing will not work if you just define __add__ because as this explains, the sum function starts with the integer 0, and 0 + YourClass will be undefined.

So, you need to define __radd__ as well. Here's an implementation that will allow you to sum:

def __radd__(self, other):
    if other == 0:
        return self
    else:
        return self.__add__(other)

Now your class should be able to sum just fine.

EDIT: (I'm aware that this does not solve OP's problem, but it solves the problem that people come to this question to solve, so I'm leaving it.)