pointer

Donn Cave donn at u.washington.edu
Tue Apr 9 13:10:38 EDT 2002


Quoth "Andrey Panchenko" <andrey at app.omsk.su>:
| "Oleg Broytmann" <phd at phd.pp.ru> wrote:
|> On Tue, Apr 09, 2002 at 04:45:08PM +0200, Henning Peters wrote:
|> > is there anything similar to the pointer concept from c/c++ in python?
|>
|>    In Python *everything* is a pointer. Really.
|>
|> > i would like to store values in two different locations. both values should
|> > always be equal. the one could be a pointer on the other. is this possible
|> > to do this in python?
|>
|> a = 1 # put a pointer to an Integer objetc into variable a
|> b = a # copy the pointer into b; now both b and a hold pointers to the same
|>       # Integer object
|>
|> c = [a, b] # make a list holding two pointers
|
| I think it's rather an ambiguous statement. I can think that after
|
| a = 1
| b = a
| a = 3
|
| b must hold 3. But it's not true. IMHO it's better to say that the python
| names are like pointers only for mutable objects.
| (Caution - newbie opinion)

Well, it's hard to use these words without some risk of confusion.
There is indeed some similarity between a Python reference and a
"pointer" in C, and all you need for your example is to bear in mind
that "b = a" means "let b point to the same object as a" - in other
words, the assignment does make a pointer of "b", but the "right hand
side" automatically dereferences pointer "a".

Meanwhile, the answer to the original question ("how can I be two places
at once") does require a mutable object.  If your two places both refer
to a single object, then when attributes of that object change, both will
see the same change.

But that's really changing the question so that it can have a positive
answer.  Whatever the relationship between Python names and pointers,
it really applies to every single object, whether mutable or immutable.

   class T:
       def __init__(self):
           self.x = 'original'
   a = T()
   b = a
   b.x = 'new'
   print a.x   (-> 'new' ... this is the mutable object strategy.)

but
   b = T()
   print a.x   (-> 'new' ... whether a and b were mutable or not, 
                             they now point to different objects.)

Mutable objects' only special property outside of their particular kinds
of mutability, is that they can be dictionary keys.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list