[Tutor] Pass by reference

ibraheem umaru-mohammed ium@micromuse.com
Wed, 11 Jul 2001 17:33:18 +0100


[Praveen Pathiyil wrote...]
-| Can we do a "pass by reference" in python ?

no. not directly.

-| Ex:
-| 
-| ( I would like to know whether there is a way to have the modified ex_dict to be visible in modified form in func1 with out explicitly returning that )
-| 
-| def func2(x, ex_dict):
-|     ex_dict[x] = x*x
-| 
-| def func1(a):
-|     ex_dict = {}
-|     func2(a, ex_dict)
-| 
-| func1(2)
-| 

You can do this in at least two ways: 
	o using a class
	o using global dictionary variable

Here is one way of achieving similar functionality using classes:

	ibraheem@ignoramus:$ python
	Python 2.1 (#1, Apr 20 2001, 17:50:32) 
	[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
	Type "copyright", "credits" or "license" for more information.
	>>> class A:
	...   def __init__(self):
	...     self.ex_dict={}
	...   def func2(self,x):
	...     self.ex_dict[x]=x*x
	...   def func1(self,a):
	...     self.func2(a)
	...   def print_items(self):   
	...     for i in self.ex_dict.items():
	...       print i
	... 
	>>> test = A()
	>>> test.func1(2)
	>>> test.print_items()
	(2, 4)
	>>> test.func1(3)
	>>> test.print_items()
	(3, 9)
	(2, 4)
	>>> 

Hope that helps a little.

Kindest regards,

		--ibs

-- 
A sad spectacle.  If they be inhabited, what a scope for misery and folly.
If they be not inhabited, what a waste of space.
		-- Thomas Carlyle, looking at the stars