passing class by reference does not work??

Hamilton, William whamil1 at entergy.com
Wed Apr 11 10:49:56 EDT 2007


> -----Original Message-----
> From: python-list-bounces+whamil1=entergy.com at python.org
[mailto:python-
> list-bounces+whamil1=entergy.com at python.org] On Behalf Of wswilson
> Sent: Wednesday, April 11, 2007 9:24 AM
> To: python-list at python.org
> Subject: passing class by reference does not work??
> 
> Here is my code:
> 
> class A():
> 	val = 0
> 
> def b(item, a):
> 	a.val = a.val + 1
> 	return item + a.val
> 
> def c():
> 	d = [1, 2, 3]
> 	print [b(item, A()) for item in d]
> 
> c()
> 
> I expected this to output [2, 4, 6]. However, it outputs [2, 3, 4]
> which is not what I wanted. I thought that if I passed the A()
> instance in my list comprehension in c(), then the changes I made to
> a.val in b() would be reflected in the A() instance next time the list
> comprehension called b(). But, obviously that is not happening. I'm
> kinda new at python so I may be missing something obvious here.
> 
> Any suggestions?

A() is not the class A.  It calls the constructor of class A, returning
an instance.  If you change that line to:

print [b(item, A) for item in d]

you'll get the output you expected.

---
-Bill Hamilton
whamil1 at entergy.com
 




More information about the Python-list mailing list