Python:乘法覆盖

发布于 2024-11-27 03:23:53 字数 144 浏览 5 评论 0原文

因此,我有一个自定义类,它具有一个可处理整数的 __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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鹿童谣 2024-12-04 03:23:53

只需将以下内容添加到类定义中即可:

__rmul__ = __mul__

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

__rmul__ = __mul__
挽心 2024-12-04 03:23:53

也实现__rmul__

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__

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__
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文