Search code examples
pythonlistsum

python's sum() and non-integer values


Is there a simple and quick way to use sum() with non-integer values?

So I can use it like this:

class Foo(object):
    def __init__(self,bar)
        self.bar=bar

mylist=[Foo(3),Foo(34),Foo(63),200]
result=sum(mylist) # result should be 300

I tried overriding __add__ and __int__ etc, but I don't have found a solution yet

EDIT:

The solution is to implement:

 def __radd__(self, other):
    return other + self.bar

as Will suggested in his post. But as always, all roads lead to Rome, but I think this is the best solution since I don't need __add__ in my class


Solution

  • Its a bit tricky - the sum() function takes the start and adds it to the next and so on

    You need to implement the __radd__ method:

    class T:
        def __init__(self,x):
            self.x = x
        def __radd__(self, other):
            return other + self.x
    
    test = (T(1),T(2),T(3),200)
    print sum(test)