覆盖 __add__ 方法后的 TypeError [英] TypeError after overriding the __add__ method
问题描述
我想了解 __add__
是如何工作的:
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)]
这有效
t=MyNum(0)
for n in d:
t=t+n
print t
但这不会:
print sum(d)
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
我做错了什么?我怎样才能让 sum() 起作用?
What am I doing wrong? How can I get the sum() to work?
更新
我的问题是如何在支持 __add__
的对象列表上使用 sum,需要尽可能保持通用.
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.
推荐答案
您还需要定义 __radd__
以使其工作.
You need to define __radd__
as well to get this to work.
__radd__
是反向添加.当 Python 尝试计算 x + y
时,它首先尝试调用 x.__add__(y)
.如果失败,则返回到 y.__radd__(x)
.
__radd__
is reverse add. When Python tries to evaluate x + y
it first attempts to call x.__add__(y)
. If this fails then it falls back to y.__radd__(x)
.
这允许您仅通过触摸一个类来覆盖加法.例如,考虑 Python 必须如何计算 0 + x
.尝试调用 0.__add__(x)
但 int
对您的类一无所知.您不能很好地更改 int
中的 __add__
方法,因此需要 __radd__
.我想这是依赖倒置的一种形式.
This allows you to override addition by only touching one class. Consider for example how Python would have to evaluate 0 + x
. A call to 0.__add__(x)
is attempted but int
knows nothing about your class. You can't very well change the __add__
method in int
, hence the need for __radd__
. I suppose it is a form of dependency inversion.
正如 Steven 指出的那样,sum
就地操作,但从 0 开始.所以第一个加法是唯一需要使用 __radd__
的加法.作为一个很好的练习,您可以检查是否是这种情况!
As Steven pointed out, sum
operates in place, but starts from 0. So the very first addition is the only one that would need to use __radd__
. As a nice exercise you could check that this was the case!
这篇关于覆盖 __add__ 方法后的 TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!