python 运算符重载,操作符重写


https://blog.csdn.net/JSWANGCHANG/article/details/90739161

需要在类中重新定义几个方法:


    # 重载加法
    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

————————————————
版权声明:本文为CSDN博主「老王笔记」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/JSWANGCHANG/article/details/90739161


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM