开发者

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

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 occur开发者_如何转开发s.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜