Python:乘法替代 [英] Python: multiplication override
本文介绍了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屋!
查看全文