Pointers
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Tue Apr 18 05:33:42 EDT 2000
Peter Halliday wrote in comp.lang.python:
> I just started learning python. I just want to make sure that I understand the
> object interaction you were discussion here. To use your statement. So x + 1
> is an object, x is an object, and y is an object. Y and x happen to both be
> pointing to x + 1. Is this right?
Sort of. x can never point to x+1 :). Rather, x = x+1 computes the result of
the expression x+1, makes a new object with that value, and makes x point to
it.
> If you then did something to y would you be doing something to x + 1?
No, not if this is about integers anyway.
> I would say, no because it is a seperate object right!
Actually, that's not the reason. y and x are both exactly the same object.
Thing is, if it's an integer, then you can't change it! You can only make a
new object and assign it to y.
> > x = x + 1
> > y = x
Now y and x are the same object. But the only way to change y, say with y=y+1,
makes a new object (the result of y+1) and lets y refer to it.
It's different with mutable objects like lists, they can be changed in place:
>>> x = [1,2]
>>> y = x # They're both the same list now
>>> x
[1, 2]
>>> y.append(3)
>>> y
[1, 2, 3]
>>> x
[1, 2, 3]
>>> y = y+[4] # This still creates a new object
>>> y
[1, 2, 3, 4]
>>> x
[1, 2, 3]
Assignment never changes an object, except when it's an assignment to some
internal of the object (like y[1] = 3).
Try playing around in the interpreter for a while, this is a key thing to
understand about Python in my opinion. You can test objects to see if
they're the same object with 'x is y', and test their values with 'x == y'.
--
Remco Gerlich, scarblac at pino.selwerd.nl
Hi! I'm a .sig virus! Join the fun and copy me into yours!
More information about the Python-list
mailing list