zzzbbx
zzzbbx

Reputation: 10161

python operator overload and friends


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

Upvotes: 1

Views: 650

Answers (3)

Terra Kestrel
Terra Kestrel

Reputation: 20364

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

Upvotes: 2

Hugh Bothwell
Hugh Bothwell

Reputation: 56714

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)

Upvotes: 2

Joril
Joril

Reputation: 20596

Define its __add__() method.

See here.

Upvotes: 3

Related Questions