用户定义的__mul__方法不是可交换的 [英] User defined __mul__ method is not commutative

查看:57
本文介绍了用户定义的__mul__方法不是可交换的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个类来表示Python中的向量(作为练习),但是在扩展内置运算符时遇到了问题。

I wrote a class to represent vectors in Python (as an exercise) and I'm having problems with extending the built-in operators.

我定义了<向量类的code> __ mul __ 方法。问题在于,在表达式 x * y 中,解释程序调用x的 __ mul __ 方法,而不是y。

I defined a __mul__ method for the vector class. The problem is that in the expression x * y the interpreter calls the __mul__ method of x, not y.

所以 vector(1、2、3)* 2 返回一个向量<2、4、6>这应该;但是 2 * vector(1、2、3)会创建TypeError,因为内置的int类不支持与用户定义的向量相乘。

So vector(1, 2, 3) * 2 returns a vector <2, 4, 6> just like it should; but 2 * vector(1, 2, 3) creates a TypeError because the built-in int class does not support multiplication by my user-defined vectors.

我可以通过简单地编写一个新的乘法函数来解决这个问题

I could solve this problem by simply writing a new multiplication function

def multiply(a, b):
    try:
        return a * b
    except TypeError:
        return b * a

,但这需要重新定义我要与用户定义的类一起使用的每个函数。

but this would require redefining every function that I want to use with my user-defined classes.

有没有办法才能使内置函数正确处理此问题?

Is there a way to make the built-in function handle this correctly?

推荐答案

如果您想对不同类型使用可交换性 您需要实现 __ rmul __() 。如果实现,将被调用,就像所有 __ r * __()特殊方法一样,如果操作否则会引发 TypeError 。注意参数已交换:

If you want commutativity for different types you need to implement __rmul__(). If implemented, it is called, like all __r*__() special methods, if the operation would otherwise raise a TypeError. Beware that the arguments are swapped:

class Foo(object):
    def __mul_(self, other):
        ''' multiply self with other, e.g. Foo() * 7 '''
    def __rmul__(self, other):
        ''' multiply other with self, e.g. 7 * Foo() '''

这篇关于用户定义的__mul__方法不是可交换的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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