0

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.

Jack Twain
  • 6,273
  • 15
  • 67
  • 107

2 Answers2

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