【再回首Python之美】【重载操作符】实例汇总

操作符示重载

每遇到一个新的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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值