Confused yet again: Very Newbie Question

Lie Lie.1296 at gmail.com
Tue Jul 8 06:45:41 EDT 2008


On Jul 7, 7:09 pm, Jeff <jeffo... at gmail.com> wrote:
> When you call c3.createJoe(c1.fred), you are passing a copy of the
> value stored in c1.fred to your function.  Python passes function
> parameters by value.

No, python doesn't pass variable either by value or by reference. The
behavior in python is a bit of mix between passing by value and by
reference, because python use different variable model than Basic (in
short, saying passing by reference or value in python doesn't make
sense). In python, variables are names referring to an object, in
Basic variables are the object itself. In python, when you pass
variable as function parameter, you pass the object to the function
and inside the function a new name is rebound to that object. These
two names are not related in any way except that they refers to the
same object.

In python an immutable object can't be changed after creation and
string is immutable, so when you reassign 'Joe' to myName, a string
object 'Joe' is created and assigned to myName, myName's original
string object ('fred') isn't affected and other names that refers to
the string object 'fred' (i.e. c1.fred, one.fred) isn't changed. If
you want to change all those values too, you'd have to change the
inner string object itself (which is impossible since string object is
immutable). If the object referred is mutable (e.g. list, dictionary)
that example would work.

> The function will not destructively modify its
> arguments; you must expliticly state your intention to modify an
> object:
>
> class one():
>     fred = 'fred'
>
> class three():
>     def createJoe(self, myName):
>         return "Joe"
>
> def main():
>     c1 = one()
>     c3 = three()
>     c1.fred = c3.createJoe() # Modify c1's attribute, fred, with the
> return value from c3.createJoe




More information about the Python-list mailing list