python:运算符重写

# 运算符重载
# 定义: 让自定义类生成的对象(实例) 能够使用运算符进行操作
# 作用: 让实例像数学表达式一样进行运算符操作
# 让程序简洁易懂
# 运算符重载方法的参数已经有了固定含义,不建议改变原  有含义

class Mynum:
    def __init__(self, data):
        self.data = data
    def __repr__(self):
        print("repr are called")
        return "Mynum({})".format(self.data)
    # 重载加法
    def __add__(self, other):
        print("__add__ are called")
        obj = Mynum(self.data + other.data)
        return obj
    #重载减法__sub__
    def __sub__(self,other):
        print("__sub__ are called")
        obj = Mynum(self.data - other.data)
        return obj
    #乘法重载___mul__    _
    def __mul__(self, other):
        print("__mul__ are called")
        obj = Mynum(self.data * other.data)
        return obj

    #除法重载___divmod__
    def __truediv__(self, other):
        print("__diymod__ are called")
        obj = Mynum(self.data / other.data)
        return obj
    #地板除: __floordiv__ //
    def __floordiv__(self, other):
        print("__floordiv__ are called")
        obj = Mynum(self.data // other.data)
        return obj
    #取模(求余数)  __mod__  %
    def __mod__(self, other):
        print("__mod__ are called")
        obj = Mynum(self.data % other.data)
        return obj
    #__pow__ 幂运算 **
    def __pow__(self, power, modulo=None):
        print("__pow__ are  called")
        obj = Mynum(self.data ** power.data)
        return obj



num1 = Mynum(100)
num2 = Mynum(200)
print("Mynum(100) + Mynum(200): {}".format(num1 + num2))
print("Mynum(100) - Mynum(200): {}".format(num1 - num2))
print("Mynum(100) * Mynum(200): {}".format(num1 * num2))
print("Mynum(100) / Mynum(200): {}".format(num1 / num2))
print("Mynum(10) // Mynum(3) :{}".format(Mynum(10)//Mynum(3)))
print("Mynum(100) % Mynum(30):{}".format(Mynum(100) % Mynum(30)))
print("Mynum(2) ** Mynum(16): {}".format(Mynum(2) ** Mynum(16)))

#练习: 实现2个自定义表相加

class Mylist:
    def __init__(self, iterable):
        self.data = [x for x in iterable]
    def __repr__(self):
        print("repr are called")
        return "Mylst({})".format(self.data)

    def __add__(self,other):
        #实现加法运算
        print("__add__ are called")
        return Mylist(self.data + other.data)
    def __mul__(self, other):
        #实现乘法运算
        return Mylist(self.data * other)
    def __rmul__(self, other):
        #左边是内建类型,右边是自定义类型
        print("__rmul__ are called")
        return Mylist(self.data * other)
    def __iadd__(self, other):
        # += 复合运算符, 就地修改,id()内存地址一致
        print("__iadd__ are called")
        self.data.extend(other.data)
        return self


lst1 = Mylist([1,2,3])
lst2 = Mylist(range(10,20))
print(lst1 + lst2)
print(lst1 * 2)
print(2 * lst1)
print("------------------------")
print(id(lst1))
lst1 += lst2
print(lst1)
print(id(lst1))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值