Python: multiplication override

两盒软妹~` 提交于 2019-12-27 12:04:55

问题


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?


回答1:


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

__rmul__ = __mul__



回答2:


Implement __rmul__ as well.

class Foo(object):
    def __mul__(self, other):
        print '__mul__'
        return other
    def __rmul__(self, other):
        print '__rmul__'
        return other

x = Foo()
2 * x # __rmul__
x * 2 # __mul__


来源:https://stackoverflow.com/questions/6892616/python-multiplication-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!