Python:乘法覆盖
因此,我有一个自定义类,它具有一个可处理整数的 __mul__ 函数。但是,在我的程序(在库中)中,它以相反的方式被调用,即 2 * x
,其中 x
属于我的班级。有没有办法让它使用我的 __mul__ 函数来实现此目的?
So, I've got a custom class that has a __mul__
function which works with ints. However, in my program (in libraries), it's getting called the other way around, i.e., 2 * x
where x
is of my class. Is there a way I can have it use my __mul__
function for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将以下内容添加到类定义中即可:
Just add the following to the class definition and you should be good to go:
也实现
__rmul__
。Implement
__rmul__
as well.