Python Forum

Full Version: Magic Method Arithmetic Operators
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is it possible to use more than 2 parameters for magic methods/Dunders for arithmetic operators? The following is my code

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Point ({self.x}, {self.y})"

    def __add__(self, other):
        return Point(self.x+other.x, self.y+other.y)

point = Point(1, 2)

other = Point(3, 5)
print(point+other)
I want to get something like
def __add__(self, other, something_else):
        return Point(self.x+other.x+something_else.x, self.y+other.y+something_else.y)
Also, for some reason the indentations dont show, so please ignore that :)
ClownPrinceOfCrime Wrote:for some reason the indentations dont show, so please ignore that
We will certainly not ignore that. Instead, you will read the BBCode help page to learn how to make the indentation show.

About the issue, how would you invoke your extended __add__ operator? If you write
obj + other + something_else
in the code, it will call
obj.__add__(other).__add__(something_else)
and not
obj.__add__(other, something_else)
the familiar arithmetic operations of addition, subtraction, multiplication, etc. are binary operation
If say you had a load of points in a collection that you wanted to add up, that could neatly be done with reduce.