Is it possible to implement operators in Python? like binary operators similar to +,- ... etc. For example I know from R that every operator is actually a function, so + is sum(x,y) or something like this. I was wondering if this can also be implemented so I can for example define a binary operator as: *. and then do something with it, like use it for matrix multiplication instead of dot() in Numpy. I'm not sure if decorators can be used to do this in python.
2 Answers
The list of special methods that can be used to implement operators can be found here: http://docs.python.org/2/reference/datamodel.html
for example, to implement a += addition operator, you can do:
class Adder(object):
def __init__(self, x):
self.x = x
def __iadd__(self, other):
self.x += other.x
return self
if __name__ == '__main__':
a1 = Adder(0)
a2 = Adder(1)
a1 += a2
print a1.x
Comments
Operators in Python are overloaded through special methods, such as __add__, __mul__ etc. That way you can only define the behaviour for the existing operators (+, *). Unlike Scala or Haskell, you cannot declare a new operator literal, such as *.. Neither you can overload an operator for a class defined before (since the implementation has to be a method).
1 Comment
user2357112
You can overload operators for existing types as long as one of the operands is of a type you're defining. You can't overload list+int or redefine tuple+tuple, though.
numpy.matrix([[1, 2], [3, 4]]) * numpy.matrix([[5, 6], [7, 8]])performs matrix multiplication.