# [SciPy-dev] Generic polynomials class (was Re: Volunteer for Scipy Project)

Sebastian Walter sebastian.walter@gmail....
Tue Oct 13 05:08:32 CDT 2009

```IMHO one should adhere to the KISS principle and separate the
algorithms from the syntactic sugar.
It also seems to me that hiding the base of the polynomial from the
user is actually a bad thing.

As far as I understood, Robert Kern suggested the following a few weeks ago:
1) define the algorithms on the coefficients as class methods to avoid
name cluttering

import numpy as np

class Polynomial(object):

def __init__(self, coeffs):
self.coeffs = np.asarray(coeffs)

def __mul__(self,rhs):
return self.__class__( self.__class__.mul(self.coeffs, rhs.coeffs) )

def __rmul__(self,lhs):
return self*lhs

def __str__(self):
return str(self.coeffs)

class PowerPolynomial(Polynomial):
@classmethod
def mul(cls, lhs_coeffs, rhs_coeffs):
return np.convolve(lhs_coeffs, rhs_coeffs, mode='full')

if __name__ == '__main__':
x = PowerPolynomial([1.,2.])
y = PowerPolynomial([3.,4.])
z = x * y

print z
print PowerPolynomial.mul([1.,2.],[3.,4.])

--------- output -----------
python poly.py
[  3.  10.   8.]
[  3.  10.   8.]

On Tue, Oct 13, 2009 at 11:12 AM, Pauli Virtanen <pav+sp@iki.fi> wrote:
> Mon, 12 Oct 2009 20:33:08 -0600, Charles R Harris wrote:
> [clip]
>> I've just gotten back and have been playing with the cat/dog/pet thing
>> just to test things out and it looks like it is going to work, I've
>> attached copies of the silly things so you can see an example of what
>> I'm thinking of. Now I'll go take a closer look at what you've been
>> doing, which I probably should have done before running on like this ;)
>
> That's sort of magicky: the user ends with instances of class named
> Polynomial, which are actually not necessarily of the same class.
>
>
> ------------
> class CatMixin:
>    def sound(self):
>        return "meow"
>
> class DogMixin:
>    def sound(self):
>        return "woof"
>
> class Pet:
>    def speak(self):
>        return self.sound()
>
>    def breed(self, other):
>        if isinstance(other, Pet):
>            return self.__class__()
>        else:
>            raise ValueError("Oh no!")
>
> class Cat(Pet, CatMixin):
>    pass
>
> class Dog(Pet, DogMixin):
>    pass
>
> dog = Dog()
> cat = Cat()
>
> print "Cat:", cat.speak()
> print "Dog:", dog.speak()
> mongrel = dog.breed(cat)
> print "Mongrel:", mongrel.speak()
> ------------
>
> Now, I'm not 100% opposed to magically generating the Mixins themselves
> with class factories, as they are a step removed from what's visible to
> the user.
>
> --
> Pauli Virtanen
>
> _______________________________________________
> Scipy-dev mailing list
> Scipy-dev@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-dev
>
```