0

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 :)

  • 2
    For start, don't use `string` as name - it's a module from standard library. – buran Jun 26 '22 at 13:22
  • @buran: Oh, I wasn't aware of that, sorry. The above is just an example of a much larger class that I am working on (with a different name of course). I quickly wrote this one, in order to post a minimal example which reproduces the problem. –  Jun 26 '22 at 13:23
  • 1
    Does this answer your question? [why there's a start argument in python's built-in sum function](https://stackoverflow.com/questions/4543129/why-theres-a-start-argument-in-pythons-built-in-sum-function). – buran Jun 26 '22 at 13:24
  • Looking at your example, I really don't see what the purpose of `_new`, `_add` and `_data` is. – buran Jun 26 '22 at 13:34
  • @buran: Thank you for the feedback. The purpose of `_new` and `_data` is to support the arithmetic operators (implemented via `__add__` and `__iadd__`) to handle both `str` operands and `string` operands. –  Jun 26 '22 at 13:49
  • My point is you can basically do the same inside the `__add__`, __iadd__`, without additional "internal" functions. – buran Jun 26 '22 at 13:56
  • @buran: In my actual class, I am implementing all of the arithmetic operators, not just `+` and `+=`, and I want each operator to support both types of input operands. So I've found that encapsulating the type checking inside a single function (named `_data`) makes for a better code reuse. –  Jun 26 '22 at 15:19

0 Answers0