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

来源:互联网 发布:mac口红膏体不光滑 编辑:程序博客网 时间:2024/05/21 09:50

         在习题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 + bTraceback (most recent call last):  File "<pyshell#8>", line 1, in <module>    a + bTypeError: unsupported operand type(s) for +: 'X' and 'X'>>> b + aTraceback (most recent call last):  File "<pyshell#9>", line 1, in <module>    b + aTypeError: unsupported operand type(s) for +: 'X' and 'X'
参考自http://stackoverflow.com/questions/4298264/why-is-radd-not-working

0 0
原创粉丝点击