A very simple question

Andrew Bennetts andrew-pythonlist at puzzling.org
Fri Aug 1 07:34:21 CEST 2003


On Thu, Jul 31, 2003 at 05:13:36PM -0800, Arnaldo Riquelme wrote:
> 
> I'm getting familiar with Python and I have a simple question:
> 
> class abc:
>     x = 100
>     y = 200
>     z = 300
> 
> 
> ac = abc()
> 
> Shouldn't I have a attribute named __dict__ for ac that contains a
> dictionary of all the variables?
> 
> Instead when I do:
> print ac__dict__
> 
> I get an empty dictionary {}
> 
> However:
> 
> print abc.__dict__    works.
> 
> I'm missing something somewhere, can anyone please enlight me on this
> matter.

You've practically answered your own question ;)

Those variables (x, y and z) are defined on the *class*, so they appear in
the class's dictionary.  Your instance doesn't have any variables of its
own, so its dictionary is empty.  Note that "print ac.x" would still print
100, because attribute lookup on instances (by default) does this:
    - first, check for the attribute on the instance
    - if not found, then check for the attribute on the class

[Similarly, attribute lookup on classes does this:
    - first, check for the attribute on this class
    - if not found, then check each of this class's immediate base classes
      in turn (more-or-less... cyclic inheritance graphs change this a
      little).  This gives a 'depth-first' search.
]

So, your code probably will work how you expect, even though the attributes
might not be where you expect them.  ;)

If you want to define those attributes per-instance automatically, write
your class like this:

class ABC:
    def __init__(self):
        self.x = 100
        self.y = 200
        self.z = 300

Now you'll get these results:
>>> a = ABC()
>>> a.__dict__
{'y': 200, 'x': 100, 'z': 300}
>>> ABC.__dict__
{'__module__': '__main__', '__doc__': None, '__init__': <function __init__
at 0x4020095c>}

-Andrew.






More information about the Python-list mailing list