Reputation: 11
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!
Upvotes: 1
Views: 142
Reputation: 32189
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
Upvotes: 6