首页 > 编程语言 > 详细

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

时间:2020-06-20 16:36:45      阅读:71      评论:0      收藏:0      [点我收藏+]

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

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

原文:https://www.cnblogs.com/qianxunman/p/13169119.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!