A very simple question

Christopher Koppler klapotec at chello.at
Fri Aug 1 05:32:50 CEST 2003


On Thu, 31 Jul 2003 17:13:36 -0800, "Arnaldo Riquelme"
<ajr at dynacap.com> 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.

These variables you defined (x, y, z) are class attributes; ac,
however is an instance of class abc, and so has no direct access to
them. However, the following gets you there in this case.

>>> print ac.__class__.__dict__
{'y': 200, 'x': 100, '__module__': '__main__', 'z': 300, '__doc__':
None}

You can test for instancehood with:
>>> isinstance(ac, abc)
True


However, what you probably wanted was to make x, y, z available to
abcs instances, which this will get you:

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

>>> ac = abc()
>>> print abc.__dict__
{'__module__': '__main__', '__doc__': None, '__init__': <function
__init__ at 0x00951230>}
>>> print ac.__dict__
{'y': 200, 'x': 100, 'z': 300}

The difference (read the tutorial
(http://www.python.org/doc/current/tut/node11.html#SECTION0011320000000000000000)
for a better explanation) is that, since you can have many instances
of any class, each of those has to have those attributes/variables
defined seperately, which you cannot do by just defining them once for
the whole class, but must do for each instance at instance creation
time (i.e. with ac = abc() in this case). 

--Christopher




More information about the Python-list mailing list