【问题标题】:Using the __mul__ method with a number and different class object使用带有数字和不同类对象的 __mul__ 方法
【发布时间】:2020-09-17 23:02:39
【问题描述】:

我正在研究一个多项式类,当两个输入都是多项式时,我想使用 mul 方法将两个不同的多项式相乘,但也能够使用该方法来乘以一个多项式带有标量。

这可能吗?我尝试搜索答案,但只得到了与为什么不能将整数和字符串相加的原因。

这是我不完整的功能。

def __mul__(self, other):
        prod = Polynomial([])
        prodDict = {}
        if isinstance(other, Polynomial):
            return Polynomial([1])

        if isinstance(other, int) or isinstance(other, float):
            for i in self.poly:
                prof.poly[i] = self.poly[i]*other
            return Polynomial([1])

错误:

Traceback (most recent call last):
File "polynomial.py", line 118, in <module>
print(p * q)
TypeError: unsupported operand type(s) for *: 'Polynomial' and 'Polynomial'

编辑:我犯了一个愚蠢的错误,并且通过制表错误将我的函数嵌套在前一个函数中。我很抱歉因为这个小错误而浪费了其他人的时间。

【问题讨论】:

  • 是的,有可能,请提供是否/您已经尝试过什么、什么/为什么不起作用等以及有关“我尝试搜索”的更多信息
  • 我认为您的问题与此非常相似:stackoverflow.com/questions/42071861/…
  • 是的,这是可能的。有关实现此类功能的技术,请参阅 magic methods
  • 我犯了一个愚蠢的错误,并且我的函数嵌套在前一个函数中,因为选项卡错误。我很抱歉因为这个小错误而浪费了其他人的时间。

标签: python


【解决方案1】:

当然可以!并且不要忘记__rmul__,否则你可能最终能够p * 5,但不能5 * p

class Poly:
    def __mul__(self, other):
        """Handle p * 5"""
        if isinstance(other, Poly):
            return ...
        elif isinstance(other, float):
            return ...
        raise TypeError(f'Cannot multiply a Poly with {type(other)}')

    """Handle 5 * p"""
    __rmul__ = __mul__

【讨论】:

    【解决方案2】:

    您尚未共享任何代码,因此我无法在此背景下展示解决方案,但这里有一个示例说明您可以如何去做:

    class Number(str):
        def __init__(self, value):
            assert isinstance(value, str)
            super().__init__()
    
        def __mul__(self, other):
            if isinstance(other, Number):
                return float(self) * float(other)
            else:
                return float(self) * other
    
        def __rmul__(self, other):
            if isinstance(other, Number):
                return float(other) * float(self)
            else:
                return other * float(self)
    
    
    s = str('test')
    a = Number('2')
    b = Number('3')
    print(a * b)
    print(4 * a)
    print(a * 5.0)
    

    结果:

    6.0
    8.0
    10.0
    

    在您的情况下,您可能会返回自己的多项式类型而不是浮点数,但想法是一样的。顺便说一句,我假设您已经知道已经有非常好的 Python 库可以解决所有这些问题 - 不要自行开发,除非您需要将其作为学术练习。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多