Using '__mul__' within a class

Martin Miller ggrp1.20.martineau at dfgh.net
Sat Sep 24 22:13:48 CEST 2005


As others have pointed out, you are just reassigning a new value to the
self argument in the Square() method shown. Instead, what you need to
do is change the object that 'self' refers to within the method. To do
this, change it to:

    def Square( self ):
        result = self * self
        self.a = result.a
        self.b = result.b
        self.c = result.c

You would also have to do something similar in an __imul__() method if
you decided to implement one.

Hope this helps,
-Martin
====

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'
> 
> ------------------------------




More information about the Python-list mailing list