I am trying to understand how __add__
works:
class MyNum:
def __init__(self,num):
self.num=num
def __add__(self,other):
return MyNum(self.num+other.num)
def __str__(self):
return str(self.num)
If I put them in a list
d=[MyNum(i) for i in range(10)]
this works
t=MyNum(0)
for n in d:
t=t+n
print t
But this does not:
print sum(d)
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
What am I doing wrong? How can I get the sum() to work?
My problem is how to use the sum on a list of objects that support the __add__
, need to keep it as generic as possible.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…