obj.__dict__ expected behavior or bug?
Erik Max Francis
max at alcyone.com
Sat Aug 9 21:37:51 EDT 2003
Ed Young wrote:
> What happened to c.a, c.b, and c.c when iterating thru
> c.__dict__ ?
>
> It appears that __dict__ members are not instantiated
> until they are changed.
>
> This precludes using __dict__ as the dictionary in
> a formatted print statement. e.g.
>
> print "c.a=%(a)s, c.b=%(b)s, c.c=%(c)s" % c.__dict__
>
> Is this a bug or expected behavior?
Expected behavior. What you're missing is the general way that Python
does attribute lookup. When c is an instance and you say c.x, Python
looks in c's __dict__ for an 'x' entry, then it looks in c's class's
__dict__ for an 'x' entry, then it looks (in a well-defined way) through
c's class's base classes, if any, for an 'x' entry in their __dict__
members.
When you defined
class C:
a = ...
b = ...
and so on, these are all _class_ attributes. When you instantiate a C
and then wrote self.a = ... in its methods, you instantiated _instance_
attributes on that instance. Class attributes are analogous to static
members/fields in other languages:
>>> class C: # class with two class attributes
... a = 1
... b = 2
...
>>> c = C()
>>> d = C()
>>> c.a
1
>>> d.a
1
>>> c.a = 10 # change an instance attribute
>>> c.a
10
>>> d.a
1
>>> C.b = 20 # change a class attribute
>>> c.b
20
>>> d.b
20
>>> C.__dict__
{'a': 1, '__module__': '__main__', 'b': 20, '__doc__': None}
>>> c.__dict__
{'a': 10}
>>> d.__dict__
{}
--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ Nobody's on nobody's side
\__/ Florence, _Chess_
More information about the Python-list
mailing list