3

In Python you can override an operation for your class (say, addition) by defining __add__. This will make it possible add class instance with other values/instances, but you can't add built-ins to instances:

foo = Foo() bar = foo + 6 # Works bar = 6 + foo # TypeError: unsupported operand type(s) for +: 'int' and 'Foo' 

Is there any way to make enable this?

2 Answers 2

6

You have to define the method __radd__(self, other) to override the operator + when your instance is on the right side.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that Python will still attempt to call __add__(), catch the exception, and then look for __radd__().
4

You cannot override the + operator for integers. What you should do is to override the __radd__(self, other) function in the Foo class only. The self variable references a Foo instance, not an integer, and the other variable references the object on the left side of the + operator. When bar = 6 + foo is evaluated, the attempt to evaluate 6.__add__(foo) fails and then Python tries foo.__radd__(6) (reverse __add__). If you override __radd__ inside Foo, the reverse __add__ succeeds, and the evaluation of 6 + foo is the result of foo.__radd__(6).

def __radd__(self, other): return self + other 

2 Comments

Very informative answer. I only have a small correction. You write the other variable references the object on the right side but it should be on the left side.
@halex: Thank you for the correction. I've definitely intended your other right.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.