0


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

Bob
  • 10,159
  • 24
  • 84
  • 136
  • 3
    Being a newbie doesn't really explain why you're not searching. No offense meant - it's generally in one's best interest to search before asking, as one usually gets more answers in less time. –  Mar 25 '11 at 22:01
  • Covered here: http://stackoverflow.com/questions/1552260/rules-of-thumb-for-when-to-use-operator-overloading-in-python – Tom Zych Mar 25 '11 at 22:30

3 Answers3

3

Define its __add__() method.

See here.

Joril
  • 18,932
  • 13
  • 69
  • 86
2
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)
Hugh Bothwell
  • 53,141
  • 7
  • 81
  • 98
2

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

JohnMetta
  • 16,952
  • 4
  • 29
  • 57