Pass by reference or by value?

Steve Holden steve at holdenweb.com
Thu Aug 16 20:40:10 EDT 2007


Thomas Jollans wrote:
> On Thursday 16 August 2007, Robert Dailey wrote:
>> Hi,
>>
>> I previously created a topic named "Pass by reference or by value" where I
>> inquired on how python's function parameters work. I received a lot of nice
>> responses, however I'm still confused on the topic. Note that I come from a
>> C++ background to Python, so any comparisons to C++ would be very helpful.
> 
> Very short answer:
> 
> Think of normal objects as always-pointers. There are no references. param = 5 
> sets the local variable "param" (be that of imaginary type int* or int, I 
> don't care) to whatever 5 is. This does not call an operator=, this plain 
> overwrites the variable.
> 
On the contrary, objects in Python are very strictly typed, and your 
thinking is a little sloppy. All names and container items are 
references. The local variable "param" doesn't *have* a type, and can be 
a reference to a value of any type.

You are right in saying that assignment isn't an operator in the 
classical sense, but don't forget that its use with qualified names 
(e.g. thing.attr = value) can result in calls to __setattr__(), which 
can be overridden under suitable circumstances.

> If you want to change arguments in that way, you can use a list as an ugly 
> hack:
> 
> def foo(param):
> 	param[0] = 5
> 	print param[0]
> 
> a = [4]
> 
> foo(a)
> 
> yeah, I said ugly. That hack makes sure that a method of the passed object is 
> called instead of of the local namespace dict. (please note that I'm throwing 
> around abstract concepts without caring about an implementation).
> 
> 
Well please stop. Some of them are bound to fall, and if you damage them 
the PSF will have to make you pay for them. Abstract concepts don't grow 
on trees, you know ;-)

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list