Varibles -- copies and references
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
222 # undesirable?
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:
>>> d=copy.copy(a) # Supposed to be a shallow copy
>>> a # But, it doesn't change the original
Is there any way to get ints/strings to refer to the same object?
Thanks and Regards,
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list