I'd like to combine a list of class instances of a class for which the __add__
method is defined.
i.e., I have a list of class instances L=[A,B,C,D]
and I want their sum E = A+B+C+D
, but generalized so that instead of the +
syntax I could do something like E = sum(L)
.
What function should I use to do that? Is the __add__
method adequate, or do I need to define a different class method (e.g. __iadd__
) in order to accomplish this?
(if this turns out to be a duplicate, how should I be asking the question?)
import operator
reduce(operator.add, L)
sum
may want to add numerical values to instances of your class. Define __radd__
so for example int
+ Foo(1)
will be defined:
class Foo(object):
def __init__(self, val):
self.val = val
def __add__(self, other):
return self.val + other.val
def __radd__(self, other):
return other + self.val
A = Foo(1)
B = Foo(2)
L = [A,B]
print(A+B)
# 3
print(sum(L))
# 3
Ignore my previous answer, it was wrong.
The reduce
function allows you to apply any binary function or method to all the elements of a sequence. So, you could write:
reduce(YourClass.__add__, sequence)
If not all objects in the sequence are instances of the same class, then instead use this:
import operator
reduce(operator.add, sequence)
Or this:
reduce(lambda x, y: x + y, sequence)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With