reference to objects

Dan Schmidt dfan at harmonixmusic.com
Fri Oct 13 18:39:07 EDT 2000


johannes at zellner.org (Johannes Zellner) writes:

| what happens in python if I assing an object to different
| variables ?
| 
| e.g.:
| 
|     class Lola:
|         def __init__(x):
|             x.y = 0
| 
|     l = Lola()
|     g = l       # <-- !!
| 
| now, does g.y = 1 modify l.y ?

Well, there's only one way to find out.  What happened when you ran
this code?

I expect you found that yes, modifying g.y does modify l.y.

| (do both variables refer to the same object ?

Yes.

Lola() makes a Lola object.

Then the 'assignment to l' makes the name 'l' refer to it.

Then the 'assignment to g' makes the name 'g' refer to the same thing
that 'l' refers to.

Once you think of assignment in Python as changing what various names
refer to, as opposed to putting things in boxes labelled with those
names (as in C), it becomes pretty natural.  I think it helps if you
call them names rather than variables.

-- 
                 Dan Schmidt | http://www.dfan.org
Honest Bob CD now available! | http://www.dfan.org/honestbob/cd.html



More information about the Python-list mailing list