[Edu-sig] Algebra + Python

Ka-Ping Yee ping@lfw.org
Sun, 6 May 2001 14:43:29 -0500 (CDT)


Hi, Kirby.

On Sun, 6 May 2001, Kirby Urner wrote:
> For example, Poly knows how to coerce a Fraction into becoming
> a polynomial of degree 0, but Fraction shouldn't ever try to
> change a polynomial into a Fraction.  So when it comes to 
> a Fraction * a Poly, it's the Poly version of * that takes
> precedence over the Fraction version -- but only because I
> type check, e.g.
> 
>     def __mul__(self,n):
>         if type(n).__name__=='instance':
>             if n.__class__.__name__ == "Poly":
>                 print "Fraction -> Poly"
>                 return n.__mul__(self)
>             if n.__class__.__name__ == "Matrix":
>                 print "Fraction -> Fraction"
>                 return n.__mul__(self)
>         
>         f = self.mkfract(n)
>         return Fraction(self.numer*f.numer,
>                         self.denom*f.denom)

Python has a built-in function "isinstance" to help you do this.
In addition, my personal preference would be to simply use *
instead of calling __mul__ explicitly, although that's more of
a style issue.  Anyway here's what i would write:

    class Fraction:
        ...
        def __mul__(self, n):
            if isinstance(n, Poly) or isinstance(n, Matrix):
                return n * self
            f = self.mkfract(n)
            return Fraction(self.numer * f.numer, self.denom * f.denom)

Very nice work, by the way!


-- ?!ng