Varibles -- copies and references

Ferdinand Sousa ferdinandsousa at gmail.com
Tue Feb 3 03:57:30 EST 2009


 People get a confused because if you pass a  mutable object inside a def
function and mutate that object the changes /are/ propagated outside--
because now you have a name inside the function and a name outside the
object both pointing to the same object.

Since tuples  are immutable, I guess passing tuples to functions would
achieve the result desired by me:
result = func ( (anobject) )

If you want a function to work on a copy of a mutable object passed to it,
and not the real object itself, you must explicitly make a copy of it.

Or using deepcopy within the function definition. This would be better as I
could simply pass an object to the function. I don't think there is another
way to make an object mutable by something in the class definition. Is
there?

>>>class AA:
         a=111

>>> x=AA()
>>> x.a
111
>>> y=x
>>> y.a
111
>>> y.a=222
>>> x.a
222                         # undesirable?
>>> z=copy.deepcopy(x)
>>> z.a
222
>>> z.a=444
>>> x.a
222
>>> y.a
222

The reason you see the "undesirable" behavior of a change to y.a showing the
same result of x.a... is because those are the *exact* same instance. You
didn't make a copy of the instance, you just made a new name and bound it to
the same instance. If you want to copy in Python you have to explicitly do
so, via the 'copy' module or any copy methods an object provides.

Could someone please give me an example of how to implement this copy method
for the AA class.

Going the other way:

>>> a=555
>>> d=copy.copy(a)             # Supposed to be a shallow copy
>>> d
555
>>> d=444
>>> a                                  # But, it doesn't change the original
555

Is there any way to get ints/strings to refer to the same object?

Thanks and Regards,
Ferdi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090203/4552f60d/attachment-0001.html>


More information about the Python-list mailing list