开发者

Python: multiplication override

开发者 https://www.devze.com 2023-03-24 08:22 出处:网络
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

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__ fun开发者_StackOverflowction for this?


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

__rmul__ = __mul__


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__
0

精彩评论

暂无评论...
验证码 换一张
取 消