Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define "__sum__" for a class

Tags:

python

oop

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__.

like image 319
Giove Avatar asked Jun 26 '18 06:06

Giove


People also ask

What is __ add __ in Python?

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.

What does __ class __ mean in Python?

__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 .

Is sum a built in class in Python?

sum is a built-in function in Python.

How do you add a method to a class 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.


1 Answers

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

like image 139
Pro Q Avatar answered Sep 26 '22 07:09

Pro Q