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)
结果如我们所想的一样: