I am trying to understand how __add__
works:
class MyNum:
def __init__(self,num):
self.num=num
def __add__(self,other):
I oppose relaying on sum() with a start point, the loop hole exposed below,
In [51]: x = sum(d, MyNum(2))
In [52]: x.num
Out[52]: 47
Wondering why you got 47 while you are expecting like …start from 2nd of MyNum() while leaving first and add them till end, so the expected result = 44 (sum(range(2,10))
The truth here is that 2 is not kept as start object/position but instead treated as an addition to the result
sum(range(10)) + 2
oops, link broken !!!!!!
Use radd
Here below the correct code. Also note the below
Python calls __radd__ only when the object on the right side of the + is your class instance eg: 2 + obj1
#!/usr/bin/env python
class MyNum:
def __init__(self,num):
self.num=num
def __add__(self,other):
return MyNum(self.num+other.num)
def __radd__(self,other):
return MyNum(self.num+other)
def __str__(self):
return str(self.num)
d=[MyNum(i) for i in range(10)]
print sum(d) ## Prints 45
d=[MyNum(i) for i in range(2, 10)]
print sum(d) ## Prints 44
print sum(d,MyNum(2)) ## Prints 46 - adding 2 to the last value (44+2)