Reference or Value?
Andrew Koenig
ark at acm.org
Sun Feb 22 13:39:01 EST 2009
"andrew cooke" <andrew at acooke.org> wrote in message
news:mailman.464.1235320654.11746.python-list at python.org...
> as far as i understand things, the best model is:
>
> 1 - everything is an object
> 2 - everything is passed by reference
> 3 - some objects are immutable
> 4 - some (immutable?) objects are cached/reused by the system
0 - Assignment rebinds the reference on its left-hand side; it does not
change the object to which that reference refers.
Example:
x = 42
y = x
Now x and y are bound to the same object
x = x + 1
This statement computes the value of x + 1, which is a new object with value
43. It then rebinds x to refer to this object, so x and y now refer to
different objects. Therefore:
def f(a):
a = a + 1
x = 42
f(x)
This example behaves analogously to the previous one: The assignment a = a +
1 binds a to a new object, so it does not affect the object to which x is
bound.
z = [3]
y = z
z[0] = z[0] + 1
The assignment rebinds z[0] to refer to a new object that has the value 4.
This rebinding does not affect the object formerly bound to z[0]. It does,
however, affect the value of the object to which z is bound, because it
changes the value of its list element. By analogy:
def g(b):
b[0] = b[0] + 1
w = [42]
g(w)
Now w[0] will be 43.
More information about the Python-list
mailing list