从双方实现__rmul__,python

问题描述 投票:2回答:2

我有办法实现rmul,以便它可以在两个方向上工作吗?我正在使用mul将元素R3中的两个向量a和b相乘。后来我希望能够将每个元素乘以一个带有2 * a和a * 2等运算符的数字。

class R3(object):
    def __init__(self,an_array):
        self.a = an_array   # of length 3
        self.s = 3 

    def __mul__(self,that):
        tmp = [0]*self.s
        for i in range(self.s):
            tmp[i] = self.a[i]*that.a[i]
        return self.__class__(tmp)

    def __rmul__(self,that):
        tmp = [0]*self.s
        for i in range(self.s):
            tmp[i] = self.a[i]*that
        return self.__class__(tmp)      

所以这适用于* b,b * a,2 * a,但不是* 2!

python class operators
2个回答
3
投票

你不能为双方都实现__rmul__,因为根据定义,__rmul__是正确的乘法。当你想改变x * y的行为时,你必须查看x.__class__.__mul__y.__class__.__rmul__

  • a * b使用R3.__mul__(OK)
  • b * a也使用R3.__mul__(OK)
  • 2 * a首先使用int.__mul__,失败,然后尝试R3.__rmul__而不是(好的)
  • a * 2使用R3.__mul__,失败,使用int.__rmul__,再次失败(不行!)

你现在写它的方式,__mul__假设that参数是一个R3实例,而__rmul__假设that参数是一个标量。

您无法修改int.__rmul__,以更改最后一种情况的行为,因为您无法修补这些内置类型。但是,您可以修改R3.__mul__以更改该行为。

你已经实现了__mul__来处理传递给R3that实例。修复它,以便它可以处理传递到that的标量。


0
投票
class NumString:
    def __init__(self, value):
        self.value = str(value)

    def __str__(self):
         return self.value

    def __int__(self):
        return int(self.value)

    def __float__(self):
        return float(self.value)

    def __add__(self, other):
        if '.' in self.value:
            return float(self) + other
        return int(self) + other

    def __radd__(self, other):
        return self + other

    def __iadd__(self, other):
        self.value = self + other
        return self.value

    def __mu1__(self, other):
        if '.' in self.value:
            return float(self) * other
        return int(self) * other

    def __rmu1__(self, other):
        return self * value
© www.soinside.com 2019 - 2024. All rights reserved.