Reputation: 1807
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?
Upvotes: 3
Views: 3295
Reputation: 34047
In [12]: class Num(int):
...: def __init__(self, number):
...: self.number = number
...: def __add__(self, other):
...: #self.number += other*100 #why do you want to do other*100?
...: return Num(self.number+
...: Num(other).number) #wrap "other" with "Num"
#in case "other" is an "int"
In [13]: num = Num(10)
...: print num+10
20
Actually, you don't need to override __add__
if your Num
is a subclass of int
. Simply call super
in __init__
would suffice:
In [19]: class Num(int):
...: def __init__(self, *args):
...: super(Num, self).__init__(args)
In [20]: Num(10)
Out[20]: 10
In [21]: Num(10)+10
Out[21]: 20
and this way no other attribute like self.number
is needed.
Upvotes: 3
Reputation: 47996
You are wanting to override the method of your class and not of one specific property.
In your implementation, num.number + 10
will not trigger your class __add__
method but rather the method of the variable you are operating on - in your case, an int
.
num.number.__add__
This is why you see the output of 20
- it uses the default __add__
10 + 10 = 20
If you want to use the method of your class, you would do it like this:
num = Num(10)
num + 10
Now you are accessing your num.__add__
method.
Upvotes: 1
Reputation: 56547
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
Upvotes: 3