An interesting python problem

bruno modulix onurb at xiludom.gro
Wed Sep 14 13:28:16 CEST 2005

Adriaan Renting wrote:
> In my mind all Python variables are some kind of "named pointers",

Technically, they are key/value pairs in a dictionnary, the key being
the name and the value a reference to an object.

> I
> find that thinking this way helps me a lot in understanding what I'm
> doing. I know that this is not completely technically correct as in the
> first two examples there is actually a new a.i/a.arr created that
> shadows A.i, but thinking like this helps me. Are there fundamental
> flaws to think this way?

You have 3 things to keep in mind here:
1/ in Python, a class is an object to, and an instance keeps a reference
to it's class object.
2/ a name is first looked up in the object's dict, then in it's class dict.
3/ when assigning to a non-existent instance attribute (ie : a.i = 1),
you're in fact just adding a new key/value pair *in the object's dict*.

> Example:
>>>>class A: 
> i = 0      ## Class A has a pointer named i pointing to (int 0 object)
>            ## A.i -> (int 0 object)

class A's dict contains a 'i' key referencing an int(0) object

>>>>a = A() ## point a.i to the same thing A.i points to
>            ## A.i -> (int 0 object)
>            ## a.i -> (int 0 object)

Since 'i' is not in a's dict, 'i' is looked up in A's dict

>>>>b = A() ## point b.i to the same thing A.i points to
>            ## A.i -> (int 0 object)
>            ## a.i -> (int 0 object)
>            ## b.i -> (int 0 object)


>>>>a.i = 1 ## point a.i to a new (int object)
>            ## A.i -> (int 0 object)
>            ## b.i -> (int 0 object)
>            ## a.i -> (int 1 object)

A new 'i' key is added to a's dict, with a reference to a int(1) object
as value

(etc, snip...)

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list