Pass by reference or by value?
Steve Holden
steve at holdenweb.com
Thu Aug 16 17:42:11 EDT 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.
>
> I ran a few tests. There's two tests in particular I wanted to show you
> guys:
> ------------------------------------------------------------------------------------------------
> myvar = []
>
> def changeme( param ):
> param.append( "blah" )
> print param
>
> changeme( myvar )
>
> print myvar
>
> The above code yields the following output:
> ['blah']
> ['blah']
>
> This means that the list passed in was modified by the function.
> ------------------------------------------------------------------------------------------------
> Now test case 2:
>
> myvar = 4
>
> def changeme( param ):
> param = 5
> print param
>
> changeme( myvar )
>
> print myvar
>
> The above code yields the following output:
> 5
> 4
>
> This means that the integer passed in was NOT modified by the function.
> ------------------------------------------------------------------------------------------------
>
> Between these two tests, both types passed in are mutable objects. I'm
> having trouble figuring out what mandates an object to be changed from
> within a function versus not. What is happening in test case 2 to cause
> it to not be modified?
>
> Thanks for reading guys. Hopefully one day I'll understand this lol.
>
The first thin to realise is that all Python names are just bindings to
values. In C++ terms you can think of them all as pointers.
De-referencing is automatic when a value is to be retrieved.
>>> def changeme( param ):
... param = 3
... print param
...
>>> myvar = []
>>> changeme(myvar)
3
>>> myvar
[]
>>>
In this case there is no attempt to mutate the argument, the argument
name is simply bound to another value. Since the argument is a name
local to the function, this does not result in any change outside the
function.
In this case the argument is bound to a mutable value, so the call to
append mutates the object (a list) referenced by the argument.
Unlike C++ and similar languages a variable does not hold a value, it
holds a pointer to a value. When a list is passed as a function argument
the reference to the list is copied into the argument. Does this help at
all?
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