1

I need to make an operators to an object and I wonder what is the best way.

for example for the operator add

can I write this in this way?

def _add_(self,other):
   new=self.add(self,other)// can I write like that?
    return new

thanks for the help!

4
  • 1
    docs.python.org/2/reference/… Take a look at that. Commented May 5, 2014 at 8:42
  • 1
    Why don't you move code from add to __add__ and use __add__ everywhere instead of add? It will save you one function call, and there will be less duplication. Commented May 5, 2014 at 8:43
  • 2
    self.add(self,other) seems to contain one self more than needed... Commented May 5, 2014 at 8:54
  • What type does self.add return? Commented May 5, 2014 at 9:31

1 Answer 1

6

You would use the python magic function __add__ to take care of the +:

Example:

class A():
    def __init__(self, num):
        self.num = num
    def __add__(self, other):
        return self.num + other

a = A(6)

>>> print a+5
11

For greater flexibility, you should also define __radd__, this is for the reverse addition case 5+a which would not work in the example above.

class A():
    def __init__(self, num):
        self.num = num
    def __add__(self, other):
        return self.num + other
    def __radd__(self, other):
        return self.num + other

>>> a = A(6)
>>> print 5+a
11
>>> print a+5
11

Or if you want to return as an object instead of an int, you can do it as:

class A():
    def __init__(self, num):
        self.num = num
    def __add__(self, other):
        return A(self.num + other)

a = A(5)
b = a+5
print b.num
10
print a.num
5

What has been demonstrated above is operator overloading. It overrides the built-in default methods for handling operators by letting the user define custom methods for the operators.

Here is a list you might find useful as to which operators can be overloaded

Sign up to request clarification or add additional context in comments.

15 Comments

might be an idea to explain to him what operator overloading is.
@user3603535, sorry meant "to her"!
yes, I see you added a link for operator overloading.
The problem with this solution is that it returns an int. If I did b = a + 5, should b be an int or an instance of class A? I vote for the latter.
there is also __iadd__ (self.num += is appropriate for it). Returning int instead of A type makes a + 6 + 1 different from a + 7 (due to side-effects) that is not intuitive.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.