calling __coerce__() method on derived classes results in an error

349 views Asked by At

My trial was like below, but it didn't work.

class MyNum:
   def __init__(self , n):
   self.n = n

class MyNum2(MyNum):
   def __coerce__(self , y):
        return self, y

   def __radd__(self, y):
        print 'radd called'
        return self.n + y.n

I typed on the python command line:

>>> x = MyNum(20)
>>> y = MyNum2(12)
>>> x+y

Result:

>>> Traceback (most recent call last):
  File "", line 1, in 
    y+x
  File "", line 3, in __coerce__
    return self.y
AttributeError: MyNum instance has no attribute 'y'

When I use the __coerce__() method without class deriving, the result of x+y equals to radd called // 32. However, with derived-class, an error occurs.

Please give me some help, and happy lunar new year, thank you in advance.

1

There are 1 answers

1
shang On

Based on the error message, your __coerce__ implementation actually had

return self.y

instead of the

return self,y

as you've written in the example code.

Your code above works for me, and you don't actually even need the __coerce__ method here. Just having the __radd__ is sufficient in your example.