1

Is there any way I can over write the sum() method to act differently on a list?

I expected I would be able to find a dunder method that would allow me to define my own implementation, but I couldn't.

That's how I'd imagine the implementation

class MyDummyList(list):
    def __sum__(self): -> str:
        return 'a'

x = MyDummyList()
print(sum(x)) -> # prints 'a'

Obviously this breaks as there is no dunder method __sum__ but I am somewhat surprised that there is no such a way to do that using dunder methods as sum is a quite common operation on iterables.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
MMM
  • 101
  • 5
  • Is there a reason you want it to be a dunder method? – Khaled Adrani May 28 '22 at 09:46
  • Not really, just expected to see it implemented as it seems a very common custom behavior on iterables, but if there is none then ok, I expected to have seen one.\ – MMM May 28 '22 at 09:47
  • 1
    Obviously, you can implement x.sum() with `sum` being an (inefficient) iterator over a class list. – S3DEV May 28 '22 at 09:49
  • still I want to use the wrapper around the object sum(iterbale) not iterable.sum() – MMM May 28 '22 at 09:53
  • 2
    This is a duplicate of https://stackoverflow.com/questions/18136507/how-to-implement-built-in-sum-of-the-class (correcting my earlier close vote) – mkrieger1 May 28 '22 at 09:54

0 Answers0