So i just started learning object oriented programming in python 3 and i came across the "__add__" method and i don't understand what " other " is and what it does. I tried to look on the internet for an answer but i found nothing, here is an example of my code:
import math
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
f = self.x + other.x
e = self.y + other.y
what " other " is and what it does.
It is the name of a parameter. The parameter other is (for example) another instance of MyClass. Take the following example:
a = MyClass(1, 2)
b = MyClass(3, 4)
# the next line calls MyClass.__add__ on the instance a
c = a + b
In this case a is self and b is other.
The code for __add__ in your example is incomplete, it should really return a new MyClass instance.
def __add__(self, other):
f = self.x + other.x
e = self.y + other.y
return MyClass(f, e)
other is nothing but an argument name. You can call it whatever you want, although methods obey some conventions to make the code clearer.
Here are some argument names that usually have a special meaning.
self: an argument expected to be the instance from which the method
was called
other: an argument expected to be an instance of the class, but not
the one calling the method
cls: the class itself
In particular, the method __add__ is called by the + operator.
self + other
... is what calls...
self.__add__(other)
class MyNumber(int):
def __add__(self, other):
print('I am', self)
print('I encountered', other)
return super().__add__(other)
x = MyNumber(2)
y = MyNumber(3)
x + y
I am 2
I encountered 3
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