python operator overload and friends

拜拜、爱过 提交于 2019-12-13 05:24:43

问题



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.

Thanks


回答1:


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)



回答2:


Define its __add__() method.

See here.




回答3:


When in doubt of the basics: manual. http://docs.python.org/reference/datamodel.html



来源:https://stackoverflow.com/questions/5438574/python-operator-overload-and-friends

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!