Search code examples
pythonpython-3.xadditionmagic-methods

python: reverse the elements of magic methods that affect operators


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?


Solution

  • 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.