我用__add__方法定义一个类Foo:class Foo():
def __init__(self, data):
self.data = data
def __add__(self, other):
return self.data + other.data
data属性只保存字符串。在
最终目标是将Foo对象的list/iterable传递给sum方法以连接字符串:
^{pr2}$
期望:foobarbaz
实际:---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 sum(s)
TypeError: unsupported operand type(s) for +: 'int' and 'Foo'
我认为sum调用object.__add__来将这两个方法相加。我知道我可以用另一种方法来解决这个问题(可能是用functools.reduce),但是有没有一种方法可以让它与sum一起工作呢?在
编辑:忘了提,试过这个:In [582]: sum(s, Foo(''))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 sum(s, Foo(''))
TypeError: Can't convert 'Foo' object to str implicitly