1

How do I overload an operator in an instanced class in Python? I know that new methods can be bound to an instanced class using the types package:

import types

class A:
    x = 2

a = A()
a.print_x = types.MethodType(lambda self: print(self.x), a)
a.print_x()
>>> 2

However, this does not intuitively work with operator methods:

a.__add__ = types.MethodType(lambda self, val: print("Adding val {}".format(val), a)
a.__add__(3) # Method is there & works...
>>> Adding val 3
a += 3 # But isn't called for +=
>>> TypeError: unsupported operand type(s) for +=: 'A' and 'int'

So how do I override these special methods? Thanks in advance!

Nearoo
  • 4,454
  • 3
  • 28
  • 39
  • You can't, see the [duplicate](https://stackoverflow.com/questions/33824228/why-wont-dynamically-adding-a-call-method-to-an-instance-work/33824320#33824320). Special methods are looked up on the type of the object, bypassing the instance. You can only ever put them on the class itself. – Martijn Pieters Jun 15 '17 at 09:37

0 Answers0