Re: Using '__mul__' within a class



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/
.



Relevant Pages

  • Re: Access modifier : private
    ... But my confusion is, even though i mark it as private, it is ... with a receiver. ... def initialize ... puts "m2 calling self.m" ...
    (comp.lang.ruby)
  • Re: Symbol#to_proc with arguments
    ... when calling a method, so passing 'l' in your example is not valid ... def to_proc ... No real reason to second-guess Ruby on this. ...
    (comp.lang.ruby)
  • Re: another newbie question: why should you use "*args" ?
    ... and is more flexible in it's calling. ... def chunk_plot: ... impossible to avoid using the *args syntax. ... like java; ...
    (comp.lang.python)
  • Re: Question about "protected" and "private"
    ... def protected_meth ... puts "hello from protected_meth" ... protected_meth #d1 is calling this method ... private methods are not accessible in a ...
    (comp.lang.ruby)
  • Re: Name conflict in class hierarchy
    ... def func: ... print 'In B.func, calling A.f1' ... functionality, and I call the new function "func". ... you don't override existing methods in that class unintentionally. ...
    (comp.lang.python)