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.
Based on the error message, your
__coerce__implementation actually hadinstead of the
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.