I am unable to make the built-in function sum
work for an array of objects of my class.
Here is an example of my attempt:
class string:
def __init__(self, data):
self.data = data
def __add__(self, other):
return self._new(other, str.__add__)
def __iadd__(self, other):
return self._set(self + other)
def __str__(self):
return self.data
def _set(self, other):
self.data = other.data
return self
def _new(self, other, op):
data = op(self.data, string._data(other))
return string(data)
@staticmethod
def _data(other):
return other.data if type(other) is string else other
a = string('a')
b = string('b')
c = string('c')
Executing print(a + b + c)
prints the string abc
as expected.
But executing print(sum([a, b, c]))
throws:
unsupported operand type(s) for +: 'int' and 'string'
Following the answers to this question, I have tried overriding function __iter__
in various different ways, but no luck.
I have even added a print
statement inside this function, but nothing was printed, implying that the function is not even executed when I execute sum
.
Thank you for helping out :)