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,741
  • 27
  • 89
  • 143
  • 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
  • 19,961
  • 13
  • 71
  • 88
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
  • 55,315
  • 8
  • 84
  • 99
2

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

JohnMetta
  • 18,782
  • 5
  • 31
  • 57