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