Python:乘法替代 [英] Python: multiplication override

查看:72
本文介绍了Python:乘法替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个自定义类,该类具有一个与int一起使用的__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?

推荐答案

只需将以下内容添加到类定义中,您应该会很好:

Just add the following to the class definition and you should be good to go:

__rmul__ = __mul__

这篇关于Python:乘法替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆