1

I am working on a class for polynomials and I would like to use the mul method to multiply two different polynomials when both inputs are polynomials, but also be able to use the method to multiply a polynomial with a scalar.

Is this possible? I tried searching for an answer, but only got hits related to why you can't add an integer and a string together.

Here is my incomplete function.

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])

Error:

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

EDIT: I made a dumb mistake and had my function nested inside the previous function by tabbing error. I apologize for wasting other's time for this trivial mistake.

martineau
  • 119,623
  • 25
  • 170
  • 301
Zed1
  • 145
  • 5
  • Yes, it is possible, please provide if / what you have already tried, what / why did not work etc. and more information on "I tried searching" – Jan Stránský Sep 17 '20 at 23:05
  • I think your question is very similar to this: https://stackoverflow.com/questions/42071861/python-commutative-operator-override – Grismar Sep 17 '20 at 23:12
  • Yes, it's possible. See [magic methods](https://stackoverflow.com/questions/2657627/why-does-python-use-magic-methods) for the techniques to implement such capabilities. – Prune Sep 17 '20 at 23:13
  • I made a dumb mistake and had my function nested inside the previous function by tabbing error. I apologize for wasting other's time for this trivial mistake. – Zed1 Sep 17 '20 at 23:25

2 Answers2

3

Of course you can! And don't forget about __rmul__, otherwise you might end up being able to p * 5 but not 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__
spagh-eddie
  • 124
  • 9
0

You haven't shared any of your code, so I cannot show a solution in context of that, but here's an example of how you could go about it:

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)

Result:

6.0
8.0
10.0

In your case, you'd probably return your own polynomial type instead of a float, but the idea is the same. By the way, I assume you're aware there already are very good Python libraries that have solved all these problems - don't roll your own, unless you need to do so as an academic exercise.

Grismar
  • 27,561
  • 4
  • 31
  • 54