For my particular problem, I wanted to sum up a list of objects and return an object, not an int. Using the class above, it would look like this:
class T:
def __init__(self, x: int):
self.x: int = x
def __add__(self, other) -> "T":
if isinstance(other, T):
return T(other.x + self.x)
else:
return NotImplemented
def __radd__(self, other) -> "T":
return self.__add__(other)
However, if you call sum() over a list of these objects:
sum([T(1), T(2)])
you will get an error similar to:
TypeError: unsupported operand type(s) for +: 'int' and 'T'
This is because sum starts with 0, and incrementally adds to that number. Adding 0 to T doesn't work. Instead, starting from Python3.8, you can set the start to be T(0), and then your summation will work:
sum([T(1), T(2)], start=T(0))
Which returns an object of class T where the attribute x = 3.
Documentation for sum: https://docs.python.org/3/library/functions.html#sum
CREDIT: Not sure how to properly credit comments, but I learned about the start= from this answer https://mcmap.net/q/414061/-python-39-s-sum-and-non-integer-values on the comment from Max https://stackoverflow.com/users/4357999/max, thank you! I really just wanted to have this as a separate answer to bring visibility to this particular use case, since SEO does not rank the comment when searching for this answer and I almost missed it myself even when reading through the solutions.
sum(test, start=T(0))
otherwise you will get an errorTypeError: unsupported operand type(s) for +: 'int' and 'str'
– Carolynncarolynne