gh at ghaering.de
Fri Apr 25 17:28:04 CEST 2003
> How does Python handles variable references/aliases?
> a = 1
A new int object with the value 1 is created. The variable a references
this int object.
> b = (REF)a
In Python: b = a
b now refers to the same object a does.
> b = 2
A new int object with the value 2 is created. b now references this int
object instead of the one with the value 1.
Objects not referenced any more (like this one) will eventually be
> print a
> In this case, since "b" is just a reference to "a", changes to "b"
> automatically change "a".
> Does python have this ability?
Sure. This, however, only works with mutable objects. ints (and strings,
and tuples) are immutable. An example for a mutable object would be a
list (or a class instance). Try this, for example:
'import site' failed; use -v for traceback
Python 2.3a2+ (#27, Apr 23 2003, 21:13:49)
[GCC 3.2.2 (mingw special 20030208-1)] on mingw32_nt-5.11
Type "help", "copyright", "credits" or "license" for more information.
>>> a =  # create a list with one element, 3
>>> b =  # create a list with one element, 4
>>> a, b # display both
>>> b = a # b references the object a refers to; nothing else
references the  list, so it will be garbage collected, eventually
>>> a,b # display both
>>> a.append(4) # append the item 4 to the list a (and b) refers to
>>> a,b # print both
([3, 4], [3, 4])
 ints are a bad excample, because they're special-cased in the
More information about the Python-list