python 类 对象 方法 sum_实现允许对对象进行“sum”操作的“add”magic方法

我用__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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值