Using '__mul__' within a class
James Stroud
jstroud at mbi.ucla.edu
Sat Sep 24 16:12:06 EDT 2005
Additionally, your __mul__() returns a new FibonnacciMatrix. You do not want a
new FibbonacciMatrix, you want to operate on an existing matrix (otherwise,
you would want to go with Ivan Voras's solution, where you re-assign outside
of the class). If you don't want the overhead of creating a instance of your
class, you may want to be more explicit in Square(), eg:
def Multiply(self, other):
self.a = self.a * other.a + self.b * other.b
self.b = self.a * other.b + self.b * other.c
self.c = self.b * other.b + self.c * other.c
def Square(self, other):
self.Multiply(other)
With __imul__(), as Terry Reedy suggested, you can also save the overhead of
creating a new instance, but it works a little differently than Square()
above, because you need to return self (assuming Square() is as above):
def __imul__(self, other):
self.Multiply(other)
return self
With these methods, __mul__() can be factored:
def __mul__(self, other):
result = FibonacciMatrix()
result.Multiply(other)
return result
Leaving all of the messiest stuff in the Multiply method.
James
On Saturday 24 September 2005 08:36, Gerard Flanagan wrote:
> Hello
>
> I'm pretty new to Python and was wondering why the 'Square' method in
> the following code doesn't work. It doesn't fail, just doesn't do
> anything ( at least, not what I'd like! ). Why doesn't 'A.a' equal 2
> after squaring?
> TIA.
>
>
> class FibonacciMatrix:
> def __init__( self ):
> self.a = 1
> self.b = 1
> self.c = 0
>
> def __mul__( self, other ):
> result = FibonacciMatrix()
> result.a = self.a * other.a + self.b * other.b
> result.b = self.a * other.b + self.b * other.c
> result.c = self.b * other.b + self.c * other.c
> return result
>
> def Square( self ):
> self *= self
>
>
> A = FibonacciMatrix()
> A.Square()
>
> print A.a #prints '1'
>
> A = FibonacciMatrix()
> B = A * A
>
> print B.a #prints '2'
>
> ------------------------------
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com/
More information about the Python-list
mailing list