运算符重载
Python允许为运算符和函数定义特殊的方法来实现常用操作
为运算符定义方法被称为运算符重载。所谓重载,就是赋予新的含义。同一个运算符可以有不同的功能。
作用:
1、让自定义的实例想内建对象一样进行运算符操作
2、让程序简洁易读
3、让自定义对象将运算符赋予新的规则
运算符和特殊方法
算术运算符 | 对应特殊方法 |
---|---|
+ | __ add__(self, other) |
- | __ sub__(self, other) |
* | __ mul__(self, other) |
/ | __ truediv__(self, other) |
// | __ floordiv__(self, other) |
% | __ mod__(self, other) |
** | __ pow__(self, other) |
运算符重载完整代码
需求: 用面向对象的方法重载加号(+)和减号(-)运算符。
完整代码:
# 运算符重载
class MyInteger:
# 创建一个自定义的整型类型
def __init__(self, data=0):
# 1、如果传入的参数是整数类型,那么直接赋值
# 2、如果传入的不是整数类型,就判断能否转化成整型
self.data = 0
if isinstance(data, int): # 判断是否为整型
self.data = data
elif isinstance(data, str) and data.isdecimal(): # 是字符串类型且为纯数字
self.data = int(data)
# 重载加号(+)
def __add__(self, other):
# 验证传入的对象是否是同一类型(MyInteger())
if isinstance(other, MyInteger):
# 返回当前对象的副本
return MyInteger(self.data + other.data)
# MyInteger()型 + int型 - 在自定义对象右侧相加整型
elif isinstance(other, int):
return MyInteger(self.data + other)
def __radd__(self, other):
return self.__add__(other)
# 相等
def __eq__(self, other):
if isinstance(other, MyInteger):
return self.data == other.data
elif isinstance(other, int):
return self.data == other
return False
# del
def __del__(self):
print(str(self.data) + "被销毁")
# 重载减号(-)
def __sub__(self,other):
return MyInteger(self.data - other.data)
def __str__(self):
# 默认调用str:一般用来返回对象的可读字符串形式(适合普通用户/使用者阅读的形式)
return str(self.data)
def __repr__(self):
# 用来将对象转换成供解释器读取的形式,一般用来方便程序员了解这个对象的底层继承关系及内存地址
return "[自定义整数类型的值]:{}\t地址:{}".format(self.data, id(self.data))
if __name__ == '__main__':
num1 = MyInteger(1024)
num2 = MyInteger(2048)
num3 = num1 + num2 # 等价:num3 = num1.__add__(num2)
print("num3 = ",num3)
num4 = num1 - num2
print("num4 = ",num4)
# 字符串类型(str) + 整型(int)
num5 = MyInteger("1024")
print("num1 + num5 = ",num1+num5)
# MyInteger()型 + int型 - 在自定义对象的右侧加整型
print("num1 + 1024 = ",num1 + 1024)
# 在自定义对象左侧加整型 - TypeError: unsupported operand type(s) for +: 'int' and 'MyInteger'
# 必须定义__radd__()方法才能在自定义对象的左侧相加整数类型
print("1024 + num1 = ",1024 + num1)
print("num1 == num2",num1 == num2)
del num1
打印结果:
num3 = 3072
num4 = -1024
num1 + num5 = 2048
2048被销毁
num1 + 1024 = 2048
2048被销毁
1024 + num1 = 2048
2048被销毁
num1 == num2 False
1024被销毁