python的运算符重载还是很方便的,记录以下代码以便回顾
class Fees:
def __init__(self, data):
"""
将字符串“num1-num2”构建成自己的数据结构
:param data:
"""
self.data = str(data)
num_list = re.findall('[\d\.]+', self.data)
self.num1, self.num2 = float(num_list[0]), float(num_list[1]) if len(num_list) > 1 else None
def __str__(self):
"""
打印出来的字符串
:return: 'num1~num2'的字符串,两个数字保留两位小数
"""
if self.num2 and self.num2 > self.num1:
return '{:.2f}~{:.2f}'.format(self.num1, self.num2)
else:
return '{:.2f}'.format(self.num1)
def __add__(self, other):
"""
重载加法运算
:param other: 另外一个Fees类型值:Fees(onum1, onum2),onum2可能为空
:return:
"""
if other.num2 is None:
return Fees(str(self.num1 + other.num1) + '-' + str(self.num2 + other.num1))
else:
return Fees(str(self.num1 + other.num1) + '-' + str(self.num2 + other.num2))
def __mul__(self, other):
"""
重载乘法运算
:param other: 另外一个Fees类型值:Fees(onum1, onum2),onum2可能为空
:return:
"""
if other.num2 is None:
return Fees(str(self.num1 * other.num1) + '-' + str(self.num2 * other.num1))
else:
return Fees(str(self.num1 * other.num1) + '-' + str(self.num2 * other.num2))
def __getitem__(self, item):
"""
重载索引
:param item:
:return:
"""
if int(item) == 0:
return float(self.num1)
elif int(item) == 1:
return float(self.num2)
def __setitem__(self, key, value):
"""
重载索引赋值
:param key:
:param value:
:return:
"""
if int(key) == 0:
self.num1 = value
elif int(key) == 1:
self.num2 = value
self.data = Fees(str(self.num1) + '-' + str(self.num2))