Consider this class where methods are added depending on the value of some parameter:
class Something(object):
def __init__(self, value, op='+'):
self.x = value
if op == '+':
self.add = self._operator
elif op == '-':
self.sub = self._operator
def _operator(self, other):
return self.x * other
x = Something(10)
x.add(3)
# 30
Now, I would like to use +
and -
operators instead of .add()
or .sub()
notation.
For this, I would write:
class Something(object):
def __init__(self, value, op='+'):
self.x = value
if op == '+':
self.__add__ = self._operator
self.__radd__ = self._operator
elif op == '-':
self.__sub__ = self._operator
self.__rsub__ = self._operator
def _operator(self, other):
return self.x * other
x = Something(10)
print(x + 3)
But instead of 30
, I get:
TypeError: unsupported operand type(s) for +: 'Something' and 'int'
despite:
print(dir(x))
# ['__add__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_operator', 'x']
What is going wrong and how could I solve this?
EDIT
This is different from Overriding special methods on an instance in that I am not trying to add a special method to an instance of an object after the object is created, i.e.:
x = Something(10)
x.__add__ = ...
But rather during class.__init__()
although, quite admittedly, both the source of the error and the solution are very similar.