473,399 Members | 3,401 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Using '__mul__' within a class

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'

------------------------------

Sep 24 '05 #1
12 2871
For the same reason that
def f(z):
z *= z
c = 1
f(c)
print c
prints 1.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDNXm7Jd01MZaTXX0RAguqAJ9u9Txaz8AOJaBn4t3v1e +ExsQ0DACgiv2l
urtGBbqtiSXWM4SKoBcP77E=
=mTpx
-----END PGP SIGNATURE-----

Sep 24 '05 #2
Gerard Flanagan wrote:
def Square( self ):
self *= self
You probably mean
return self * self
A = FibonacciMatrix()
A.Square()


Make this
A = A.Square()
Sep 24 '05 #3

"Gerard Flanagan" <gr********@yahoo.co.uk> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
def __mul__( self, other ):
def Square( self ):
self *= self


Among the other reasons cited, I believe that 'op=' maps to a different
special method than 'op'. __imul__? or something? do check.

tjr

Sep 24 '05 #4
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/
Sep 24 '05 #5
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/
Sep 24 '05 #6
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'

------------------------------


Sep 24 '05 #7
Shoot, Square() should be:

def Square(self):
self.Multiply(self)

Forgot to proofread before hitting send.

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Sep 24 '05 #8
On Saturday 24 September 2005 09:07, je****@unpythonic.net wrote:
For the same reason that
def f(z):
z *= z
c = 1
f(c)
print c
prints 1.

Jeff


I don't mean to be rude, but this is a horrible example if your are intending
to help a neophyte:

py> 1*1
1

See what I mean?

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Sep 24 '05 #9
Oops!

I should have used '2' in the example, or some other number.

I was trying to make a point about what
x *= ...
means when it is in the context of a function (or method) body.
I think this is key to understanding what Python did in the case the user posted.

Being rude wasn't my intent at all.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDNbrxJd01MZaTXX0RAmD0AJ9/kqPDQPv9TsnIYjGWJ6+huc7kkACgit9R
Ux0e1O+8FeSx6oeEgBhyDiM=
=qFsK
-----END PGP SIGNATURE-----

Sep 24 '05 #10
>>>>> James Stroud <js*****@mbi.ucla.edu> (JS) wrote:
JS> def Multiply(self, other):
JS> self.a = self.a * other.a + self.b * other.b
JS> self.b = self.a * other.b + self.b * other.c
JS> self.c = self.b * other.b + self.c * other.c


I gues this will give the wrong result because the calculation of self.b is
supposed to use the original value of self.a, not the newly calculated one.
Similar for self.c. The following should do that:

self.a, self.b, self.c = (self.a * other.a + self.b * other.b,
self.a * other.b + self.b * other.c,
self.b * other.b + self.c * other.c)
--
Piet van Oostrum <pi**@cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: pi**@vanoostrum.org
Sep 24 '05 #11
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

Sep 24 '05 #12
"Gerard Flanagan" <gr********@yahoo.co.uk> writes:
[...]
class FibonacciMatrix: [...] def Copy( self ):

[...]

__copy__ would be a more standard name. Then:

import copy
fm = FibonacciMatrix()
fm2 = copy.copy(fm)
I suppose you could also add:

__deepcopy__ = __copy__
in the body of the class definition.
John

Sep 25 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: John F Dutcher | last post by:
I use code like the following to retrieve fields from a form: recd = recd.append(string.ljust(form.getfirst("lname",' '),15)) recd.append(string.ljust(form.getfirst("fname",' '),15)) etc.,...
2
by: Thomas Philips | last post by:
To compute the product of a list of numbers, I tried entering >>>reduce(__mul__,) Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel- reduce(__mul__,) NameError: name...
28
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()',...
3
by: Colin J. Williams | last post by:
Python advertises some basic service: C:\Python24>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> With...
2
by: Kent Lewandowski | last post by:
hi all, Recently I wrote some stored procedures using java jdbc code (admittedly my first stab) and then tried to implement the same within java packages (for code reuse). I encountered...
3
by: Pranav Shah | last post by:
What is the differrence between using the "using" caluse outside of the namespace definition and inside the namespace. Example Outside: using System; namespace Example.Outside { }
12
by: Joe | last post by:
Hello All: Do I have to use the LoadControl method of the Page to load a UserControl? I have a class which contains three methods (one public and two private). The class acts as a control...
14
by: Mohamed Mansour | last post by:
Hey there, this will be somewhat a long post, but any response is appreciated! I have done many PInvoke in the past from C++ to C#, but I did PInvoke within C# not C++/CLI. Can someone explain...
15
by: r0g | last post by:
Hi There, I know you can use eval to dynamically generate the name of a function you may want to call. Can it (or some equivalent method) also be used to do the same thing for the variables of a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.