Using '__mul__' within a class

Gerard Flanagan grflanagan at yahoo.co.uk
Sat Sep 24 17:41:06 EDT 2005


Thanks for all the replies - you are very nice people!

Don't worry Jeff, I assumed you weren't telling me what 1*1 equals!  I
got your point.

James Stroud impressively got to the heart of what I was trying to do -
which was just to wrap up the code here:

en.wikipedia.org/wiki/Fibonacci_number_program#Matrix_equation

in object-oriented fashion but without too much overhead - I appreciate
you taking the time James! Thanks.

I managed to do what i wanted with the code below, though there's
definitely a lack of understanding on my part with respect to how
Python works - binding/re-binding? - that I'll have to study.

Cheers 'n' all

class FibonacciMatrix:
    def __init__( self ):
        self.a = 1
        self.b = 1
        self.c = 0

    def Copy( self ):
        copy = FibonacciMatrix()
        copy.a = self.a
        copy.b = self.b
        copy.c = self.c
        return copy

    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 __pow__( self, N ):
        if N == 1:
            return self
        if N & 1 == 0:
            return pow( self * self, N/2 )
        else:
            return self * pow( self * self, (N-1)/2 )


A = FibonacciMatrix() ** 8

print '------------------------------'
print A.a




More information about the Python-list mailing list