您的位置:首页 > 编程语言 > Python开发

python核心编程学习笔记-2016-08-15-01-左加法__add__和右加法__radd__

2016-08-15 21:38 543 查看
         在习题13-20中,出现了__radd__()函数。

         __radd__(self, other)和__add__(self, other)都是定制类的加法,前者表示右加法other + self,后者表示左加法self + other。

        python在执行加法a + b的过程中,首先是查找a是否有左加法方法__add__(self, other),如果有就直接调用,如果没有,就查找b是否有右加法__radd__(self, other),如果有就调用此方法,如果没有就引发类型异常。

        但是要注意,__radd__(self, other)的调用是有前提的,就是self和other不能是同一个类的实例。比如下面的例子:

>>> class X(object):
def __init__(self, x):
self.x = x
def __radd__(self, other):
return X(self.x + other.x)

>>> a = X(5)
>>> b = X(10)
>>> a + b

Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
a + b
TypeError: unsupported operand type(s) for +: 'X' and 'X'
>>> b + a

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
b + a
TypeError: unsupported operand type(s) for +: 'X' and 'X'
参考自http://stackoverflow.com/questions/4298264/why-is-radd-not-working
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 编程