reference to objects

Alex Martelli aleaxit at yahoo.com
Fri Oct 13 17:51:26 EDT 2000


"Johannes Zellner" <johannes at zellner.org> wrote in message
news:slrn8uessj.4r4.johannes at kristine.zellner.org...
> Hello,
>
> what happens in python if I assing an object to different
> variables ?

Each variable (and/or other 'slot' -- "cell" in a list, key
or entry in a dict, etc) will then refer to the same object.

>     class Lola:
>         def __init__(x):
>             x.y = 0
>
>     l = Lola()
>     g = l       # <-- !!
>
> now, does g.y = 1 modify l.y ?
> (do both variables refer to the same object ?

Yes, and yes.

If you want a COPY of the object, rather than a reference
to the same object, you can ask for it explicitly:

    import copy
    g = copy.copy(l)

NOW, g.y=1 does not modify l.y -- the variables are in
fact now referring to different, separate objects (that
start out as copies of each other).  (You can also use
copy.deepcopy if you want to make absolutely sure
that the _sub-parts_ of the object are also copied, but
this is rarely needed).

You can also check...:
    if g is l:
        print "same!"
    else:
        print "distinct",
        if g == l:
            print "but equal"
        else:
            print "and different"

Another way you can check...:
    if id(g)==id(l):
        print "same identity!"
    else:
        print "distinct identities"


Alex






More information about the Python-list mailing list