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.

3
  • Well since Numpy does it, it must be possible, don’t you agree? Commented Mar 3, 2014 at 10:08
  • @KonradRudolph Numpy doesn't do it! Commented Mar 3, 2014 at 10:13
  • It totally does: numpy.matrix([[1, 2], [3, 4]]) * numpy.matrix([[5, 6], [7, 8]]) performs matrix multiplication. Commented Mar 3, 2014 at 11:22

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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).

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.