在派生类上调用 __coerce__() 方法会导致错误
我的试验如下,但没有成功。
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
我在 python 命令行中输入:
>>> x = MyNum(20)
>>> y = MyNum2(12)
>>> x+y
结果:
>>> 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'
当我使用 __coerce__() 方法而不进行类派生时,结果为 x+y
等于 radd 调用 // 32
。但是,对于派生类,会发生错误。
请给我一些帮助,祝农历新年快乐,提前谢谢。
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 ofx+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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据错误消息,您的 __coerce__ 实现实际上具有
而不是
您在示例代码中编写的内容。
上面的代码对我有用,实际上您甚至不需要这里的 __coerce__ 方法。在您的示例中,只需使用
__radd__
就足够了。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.