Pointers
Neel Krishnaswami
neelk at brick.cswv.com
Wed Mar 15 18:16:28 EST 2000
Curtis Jensen <cjensen at bioeng.ucsd.edu> wrote:
>
> Pointers are sometimes useful. I have a module that creates a
> dictionary. I want to include some elements from the distionary in
> one class and other elements in another class. If I had pointers, I
> could do that. Is there another way?
Python variables have pure reference semantics, rather than boxes that
store values, including the address of other values. Thinking of them
in these terms will confuse you, though.
Think of a Python variables as labels, pasted to the object it
refers to. When the variable is rebound, then the label is peeled
off the object and stuck to the new object.
Now take something like this:
>>> a = [1,2,3]
>>> b = a
>>> b.append(4)
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>> if a == b: print "true"
...
true
When a was bound to [1,2,3,4], a list was created and a assigned to
that. Then, b was bound to the object a pointed at. Since b pointed
to the same object as a, when b was mutated (with the append), a also
changed.
Now, look at:
>>> a = 5500
>>> b = a
>>> print a, b
5500 5500
>>> a = a + a
>>> print a, b
11000 5500
If you think in terms of C pointers, you will wonder why b isn't 11000
like a is. Here is what happens conceptually:
The label a was pasted to an Integer object (5500, in this case). Then
b was also attached to the same object. When a was reassigned to a +
a, a new integer (11000) was created and a pasted anew to that. But b
wasn't rebound, so it still points to the original integer (5500).
Neel
More information about the Python-list
mailing list