2

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?

Giuppox
  • 1,393
  • 9
  • 35

3 Answers3

3

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.

norok2
  • 25,683
  • 4
  • 73
  • 99
3

Implement __radd__ (or other __r* methods):

class Value:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.value + other

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


x = Value(5)
print(x + 2)
print(2 + x)
AKX
  • 152,115
  • 15
  • 115
  • 172
0

you should use __radd__, __r*__ methods are python magic methods that make an object make something when is taken from the __add__ of another object.
Try with something like this.

class Value(): 
   def __init__(self,value): 
      self.value = value 
   def __add__(self,other): 
      return self.value + other 
   __radd__ = __add__ 

x = Value(5) 
print(x+1 == 1+x) // True