【再回首Python之美】【重载操作符】实例汇总
2018-02-24 11:00
274 查看
操作符示重载
每遇到一个新的Python操作符,就追加实例到此。已有示例操作符
__add__(self, other), 针对self+other以及obj=self+other调用__iadd__(self,other), 针对self+=other调用
待追加
重载时的注意点
1)__add__(self,other),应该返回一个类对象,即self.__class__的对象2)__iadd__(self, other),必须返回self本身。下面为校验+=重载代码书写正确性的伪码:
id1 = id(a)
a+=b
id2 = id(a)
if id1 == id2:
说明+=返回了self本身,即+=重载代码__iadd__(self, other)返回ok
else:
说明+=操作符未返回self本身,即+=重载代码__iadd__(self, other)编写错误
3)待追加
如果没有调用没有重载的操作符会抛出异常print "======================未重载操作符会抛出TypeError异常=================================="
class CTime(object):
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
t1 = CTime(1,10)
t2 = CTime(1,20)
try:
t3 = t1 + t2
except:
print "#TypeError: unsupported operand type(s) for +: 'CTime' and 'CTime'"执行结果
__add__()
__iadd__()
__*add__(self,other)重载实例#ex_add.pyself_file = __file__
#重载操作符,可以实现对象之间的+、-、+=、-=等各种操作运算
#__add__(self,other) 针对obj = self+other以及self+other的调用
#__iadd__(self, other) 针对self += other的调用
print"\r\n============重载__*add__(self, other)操作符======================="
class CTime(object):
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
def __str__(self):
return "%d:%d" % (self.hour, self.minute)
__repr__ = __str__
def __add__(self, other):#self+other调用
print 'invoke __add__(self, other)'
return self.__class__(self.hour + other.hour, self.minute + other.minute)
def __iadd__(self, other):#self+=other调用
print 'invoke __iadd__(self, other)'
self.hour += other.hour
self.minute += other.minute
return self
t1 = CTime(1,20)
t2 = CTime(1,30)
print "a+b"
t1+t2 #invoke __add__(self, other)
t2+t1 #invoke __add__(self, other)
print "\r\nobj = a+b"
t4=t1+t2#invoke __add__(self, other)
t1=t1+t2#invoke __add__(self, other)
t1=t2+t1#invoke __add__(self, other)
print "\r\n+="
t1+=t2 #invoke __iadd__(self, other)
print "exit ",self_file执行结果
(end)
相关文章推荐
- python套接字流重定向实例汇总
- python中os操作文件及文件路径实例汇总
- python中os操作文件及文件路径实例汇总
- Python实现list反转实例汇总
- 【再回首Pyhon之美】【内置函数】实例汇总
- 【再回首Python之美】【类】类数据属性和实例数据属性的基本使用
- Python中正则表达式的用法实例汇总
- Python实现list反转实例汇总
- python中os操作文件及文件路径实例汇总
- python套接字流重定向实例汇总
- 【再回首Python之美】【模块】模块汇总更新
- 【再回首Python之美】【类】通过dir()和__dict__查看一个类的属性和一个实例对象的属性
- python中os操作文件及文件路径实例汇总
- Python中正则表达式的用法实例汇总
- python基础1-类属性和实例属性
- python 请求http 实例
- 史上最全Python知识点汇总【续】
- Python 实例方法、@staticmethod和@classmethod
- python实现类的静态变量用法实例
- 用实例说明python的*args和**kwargs用法