Who modified my local variable?

Michael L Torrie torriem at chem.byu.edu
Tue Jun 13 11:17:13 MDT 2006


On Tue, 2006-06-13 at 10:31 -0600, Jacob Fugal wrote:
<snip>
> So you can see from the first call that the variable is *not* passed
> by reference; assigning to c has no effect on x, as it did in the C++
> example. But my_func2 demonstrates that we're not passing the string
> by value (copying) either, since the same object is referred to by
> both c and x; mutating c with the in-place #capitalize! message
> affected x as well. This is because both c and x did refer to the same
> object. What c and x contain are not the object itself, but references
> (pointers, basically) to the object. That reference is passed by
> value, so assignment in my_func1 only overwrites the copied reference
> and not the referred to object, yet my_func2 can operate on that
> reference and be working with the same object.

Python is the exact same way.  variable names are simply bindings.  In
Java, C++, and other languages, the idea of variables and variable names
are used interchangeably, which leads to a lot of confusion (as we have
seen).  As I learn python, I suddenly realize that all of the theory I
learned in CS 330 (Intro to Computer Languages, or Scheme) suddenly
becomes very applicable.  In Scheme we spent a huge amount of time on
bound vs free variables, etc.

In python, as in Ruby, the objects are passed by reference, but
rebinding a parameter variable name to a new object does not change the
original object.  However if you modify the object that the parameter
was bound to, the object in the caller is modified (it is the same
object).  Very subtle but also quite intuitive.  The C notion of the
variable name being the variable probably something we should never have
done.

Michael


> 
> Jacob Fugal
> 
> /*
> PLUG: http://plug.org, #utah on irc.freenode.net
> Unsubscribe: http://plug.org/mailman/options/plug
> Don't fear the penguin.
> */
> 




More information about the PLUG mailing list