Search code examples
pythonmagic-methodspython-3.x

How can I override magic methods?


Today, I was reading a book about python and I got to know that there are some magic methods such as __add__ and __mul__.

But, in the book, there is no explanation on how to use them.

So, I tried to figure it out by myself. But, I couldn't figure out how to override magic methods. Here is the code I tried.

>>> class Num(int):
...     def __init__(self, number):
...             self.number = number
...     def __add__(self, other):
...             self.number += other*100
...             return self.number
... 
>>> num = Num(10)
>>> num.number + 10
20

Could anyone please help me understand how these magic methods work?


Solution

  • class Num:
        def __init__(self, number):
            self.number = number
        def __add__(self, other):
            self.number += other*100
    
    >> num = Num(10)
    >> num.number
    10
    >> num + 10  # note that you are adding to num, not to num.number
    >> num.number
    1010
    

    That's how overriding __add__ works. Version with return:

    class Num:
        def __init__(self, number):
            self.number = number
        def __add__(self, other):
            return self.number + other*100
    
    >> num = Num(10)
    >> num.number
    10
    >> num + 10  # again adding to num
    1010
    >> num.number
    10
    

    So basically when Python sees

    x + y
    x += y
    x * y
    x *= y
    etc
    

    it translates it to

    x.__add__(y)
    x.__iadd__(y)
    x.__mul__(y)
    x.__imul__(y)
    etc