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.
Asked
Active
Viewed 1,131 times
0

Jack Twain
- 6,273
- 15
- 67
- 107
-
Well since Numpy does it, it *must* be possible, don’t you agree? – Konrad Rudolph Mar 03 '14 at 10:08
-
@KonradRudolph Numpy doesn't do it! – Jack Twain Mar 03 '14 at 10:13
-
It totally does: `numpy.matrix([[1, 2], [3, 4]]) * numpy.matrix([[5, 6], [7, 8]])` performs matrix multiplication. – Konrad Rudolph Mar 03 '14 at 11:22
2 Answers
0
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

Colin Bernet
- 1,354
- 9
- 12
0
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).

bereal
- 32,519
- 6
- 58
- 104
-
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. – user2357112 Mar 03 '14 at 10:15