Using '__mul__' within a class

James Stroud jstroud at mbi.ucla.edu
Sat Sep 24 21:49:12 CEST 2005

```I think the gist of your problem is that you are re-binding self in the
method. Here is a simpler example of your problem:

py> def doit(c):
...   c = 5
...   print "c in the method is", c
...
py> c = 42
py> print "c before calling the method is", c
c before calling the method is 42
py> doit(c)
c in the method is 5
py> print "c after calling the method is", c
c after calling the method is 42

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/

```