i am trying, just for exercise, to create a python object that can contain a number with arbitrary decimals. Everything works fine but i'm having problems with making the object interact with mathematical operators. This is how you can reproduce the error:
class Value():
def __init__(self,value):
self.value = value
def __add__(self,other):
return self.value + other
x = Value(5)
print(x+2) # this works fine: 7
print(2+x) # this doesn't work: TypeError: unsupported operand type(s) for +: 'int' and 'Value'
the same thing happens with all the other mathematic operations, is there something i can do to avoid this?
You missed implementing __radd__
:
class Value():
def __init__(self,value):
self.value = value
def __add__(self,other):
return self.value + other
__radd__ = __add__
x = Value(5)
print(x+2)
# 7
print(2+x)
# 7
More on it in the Python docs discussing emulating numeric types and the operator
module.