Re: working with pointers
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: working with pointers

From: Steven Bethard <steven.bethard@gmail.com>
Date: Tue May 31 2005 - 21:13:00 CEST

Michael wrote:
> if i do
> a=2
> b=a
> b=0
> then a is still 2!?
>
> so when do = mean a reference to the same object and when does it mean make
> a copy of the object??

It *always* means a reference. It *never* makes a copy.

Although the terminology isn't quite right, you can think of all
"variables" in Python being "references". Assignment statements in
Python then simply change the object that a "variable" "points" to.

Your example with integers:

py> a = 2
py> b = a
py> b = 0
py> a
2
py> b
0

A simlar example with lists:

py> a = [5, 7]
py> b = a
py> b = []
py> a
[5, 7]
py> b
[]

Of course, if you modify an object while two names are bound to it ("two
variables hold pointers to it") then the modifications will be visible
through either name ("either pointer"):

py> a = [5, 7]
py> b = a
py> a.pop()
7
py> a
[5]
py> b
[5]

Note that since integers are immutable, I can't give you a direct
example like this with integers, but try:

py> class I(int):
... pass
...
py> a = I(42)
py> a
42
py> b = a
py> b
42
py> a.flag = True
py> b.flag
True
py> a.flag = False
py> b.flag
False

So even with ints (or at least a mutable subclass of ints),
modifications made to an object through one name ("reference") are also
visible through other names ("references") to that object.

HTH,

STeVe
Received on Thu Sep 29 16:17:21 2005