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
- python核心编程学习笔记-2016-08-15-01-左加法__add__和右加法__radd__
- python __add__和__radd__
- python学习之类特殊方法定制 __add__,__iadd__,__radd__
- python 核心编程 第六章 习题16 矩阵加法和乘法
- 学习笔记之01-加法计算器
- python核心编程学习笔记-2016-08-26-01-文件传输
- python核心编程学习笔记-2016-08-13-01-类属性和实例属性
- python核心编程学习笔记-2016-08-28-01-习题18-4和习题18-9
- 加法编程
- python核心编程学习笔记-2016-08-13-03-授权
- python核心编程学习笔记【2016-10-08】
- python核心编程学习笔记-2016-07-18-01-print
- Python核心编程学习笔记-2016-08-13-02-绑定、静态方法和类方法
- Python核心编程学习笔记-2016-07-24-01-理解copy和deepcopy
- Python-核心编程-学习笔记
- 《python核心编程》学习笔记
- 《Python核心编程》学习笔记
- 《python核心编程》学习笔记
- 【杭电oj2036】改革春风吹满地
- JAVA对Mysql进行连接、插入、修改、删除操作
- hello csdn
- windows下caffe之训练mnist
- 数据库操作数据均乱码
- python核心编程学习笔记-2016-08-15-01-左加法__add__和右加法__radd__
- UVA 1025 A Spy in the Metrog
- MVC三层模型(struts+spring+hibernate)总结
- 华为OJ 初级 合唱队
- Kafka系列之-Kafka入门
- 【UVa】10328 - Coin Toss(递推 & 对立事件 & java)
- 2k进制数
- 1.python爬虫抓取单一网页
- 数据结构实验之图论七:驴友计划(最短路径之Dijkstra算法+Bellman-Ford算法)