python中的运算符重载_python中的运算符重载

Python中的运算符重载问题

学过C++的都知道我们在类中可以对运算符进行重载,以使运算符实现自己所需要的功能

自然在python中也可以实现运算符的重载

方法名        重载的操作说明        调用表达式

__init__    构造函数        创建对象:class()

__del__        析构函数        释放对象的时候

__add__        “+”            x + y

__or__        “|”            x | y

__repr__    打印,转换        print x, `x`

__call__    函数调用        X()

__getattr__    属性引用        x.undefined

__getitem__    索引            x[key],for循环,in测试

__setitem__    索引赋值        x[key] = value

__getslice__    分片            x[low:high]

__len__        长度            len(x)

__cmp__        比较            x == Y ,x < y

__radd__    右边的操作符"+"        非实例 + x

见下面的例子:

class example(object):

def __init__(self,x=0.0,y=0.0):

self.x = x

self.y = y

def __str__(self):

return "(%s, %s)"%(self.x, self.y)

def __add__(self,rhs):

return example(self.x + rhs.x,self.y + rhs.y)

def __sub__(self,rhs):

return example(self.x - rhs.x,self.y - rhs.y)

@classmethod

def calculate(cls,a,b):

return cls(b[0] - a[0],b[1] - a[1])

point1 = (10.0,30.0)

point2 = (25.0,50.0)

point12 = example.calculate(point1,point2)

print "point12 + (4,6) is",point12 + example(4,6)

print "point12 - (4,6) is",point12 - example(4,6)

结果如我们所想的一样:

0818b9ca8b590ca3270a3433284dd417.png





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值