python-运算符重载

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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值