python运算符重载和朋友

python运算符重载和朋友

本文介绍了python运算符重载和朋友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想知道是否有人可以给我一个关于如何在类中重载运算符的示例,在我的情况下是+运算符.我可以定义一个功能(不是类方法)吗?我是新手,所以我真的不知道该怎么做.


I wanted to know if anyone could give me an example of how to overload an operator within a class, in my case the + operator. Could I define a function (not a class method) that does it? I'm a newbie so I don't really know how to do it.

谢谢

推荐答案

class MyNum(object):
    def __init__(self, val):
        super(MyNum,self).__init__()
        self.val = val

    def __add__(self, num):
        return self.__class__.(self.val + num)

    def __str__(self):
        return self.__class__.__name__ + '(' + str(self.val) + ')'

print(MyNum(3) + 2)   # -> MyNum(5)

这篇关于python运算符重载和朋友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:26