Overload operator of instanced objects in Python

时间:2017-06-15 09:29:14

标签: python operator-overloading instance

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!

0 个答案:

没有答案