Is there something like a __sum__
method, similar to __add__
, in order to sum up a list of instances of classes into a new class instance?
I need this because in my case sum([a,b,c])
should be different from sum([sum([a,b]), c])
. In other words, the sum really depends on an arbitrary number of arguments, and cannot be defined in terms of a binary operation __add__
.
The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1. __add__(obj2). For example, let's call + on two int objects: n1 = 10.
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
sum is a built-in function in Python.
The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations. The method can also be defined outside the scope of the class.
Summing will not work if you just define __add__
because as this explains, the sum
function starts with the integer 0
, and 0 + YourClass
will be undefined.
So, you need to define __radd__
as well. Here's an implementation that will allow you to sum:
def __radd__(self, other):
if other == 0:
return self
else:
return self.__add__(other)
Now your class should be able to sum just fine.
EDIT: (I'm aware that this does not solve OP's problem, but it solves the problem that people come to this question to solve, so I'm leaving it.)
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