【发布时间】:2015-07-01 09:43:19
【问题描述】:
我有一个类定义为
class MyClass(object):
def __init__(self, value=0):
self.value = value
def __add__(self,other):
return MyClass(self.value + other.value)
__radd__ = __add__
我只想像这样对它们应用sum 函数:
a=MyClass(value=1)
b=MyClass(value=2)
c=[a,b]
print sum(c) # should return a MyClass instance with value 3
正如this post 中所建议的那样。但是,会引发异常:
15
16 c=[a,b]
---> 17 print sum(c)
TypeError: unsupported operand type(s) for +: 'int' and 'MyClass'
我不明白为什么sum 函数要添加两种不同的类型。
【问题讨论】:
标签: python list python-2.7