Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "other" mean in python?

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
like image 684
Costel biju Avatar asked Jun 15 '26 19:06

Costel biju


2 Answers

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)
like image 93
Thomas Avatar answered Jun 17 '26 08:06

Thomas


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)

Example

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

Output

I am 2
I encountered 3
like image 35
Olivier Melançon Avatar answered Jun 17 '26 08:06

Olivier Melançon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!