Python运算符用于内置类。但是相同的运算符对不同的类型有不同的行为。例如,+运算符将对两个数字执行算术加法、合并两个列表并连接两个字符串。
Python中的这一功能允许同一运算符根据上下文具有不同的含义,称为运算符重载。
那么,当将它们与用户定义类的对象一起使用时会发生什么呢?
示例 :下面的类,它试图在二维坐标系中模拟一个点。
- class Point:
- def __init__(self, x = 0, y = 0):
- self.x = x
- self.y = y
现在,运行代码并尝试在Python shell中添加两个点。
- p1 = Point(2,3)
- p2 = Point(-1,2)
- print(p1 + p2)
打印输出没有达到预想的效果。
但是,如果在类中定义str()方法,可以控制它的打印输出方式。把这个加到的类中。
示例
- class Point:
- def __init__(self, x = 0, y = 0):
- self.x = x
- self.y = y
- def __str__(self):
- return "({0},{1})".format(self.x,self.y)
现在,让print()再次尝试该函数。
- p1 = Point(3,7)
- print(p1)
要重载+符号,将需要在类中实现add()函数。拥有权利的同时也被赋予了重大的责任。可以在此函数内做任何喜欢的事情。但是返回坐标和的Point对象是明智的。
示例
- class Point:
- def __init__(self, x = 0, y = 0):
- self.x = x
- self.y = y
- def __str__(self):
- return "({0},{1})".format(self.x,self.y)
- def __add__(self,other):
- x = self.x + other.x
- y = self.y + other.y
- return Point(x,y)
测试一下:
- p1 = Point(2,3)
- p2 = Point(-1,2)
- print(p1 + p2)