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

【再回首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.py
self_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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: