obj.__dict__ expected behavior or bug?

Ed Young ejy712 at comcast.net
Sun Aug 10 03:01:24 CEST 2003


Here is an example of the behavior:
------- code start -----------------------------------
#!/usr/bin/python
#bugtest - test of class attribute initiation


class Config:
    a = 1
    b = 2
    c = 3
    d = None
    e = None
    h = {'d' : 22, 'e' : 33}

    def __init__(self, factor):
        for attr in self.h.keys():
            self.__dict__[attr] = self.h[attr] * factor

    def moda(self):
        self.a *= 5


c = Config(2)
print c.a, c.b, c.c, c.d, c.e
for attr in c.__dict__:
    print 'c.%s = %s' % (attr, c.__dict__[attr])
print

c.moda()
print c.a, c.b, c.c, c.d, c.e
for attr in c.__dict__:
    print 'c.%s = %s' % (attr, c.__dict__[attr])
print
------- code ends -----------------------------------
------- output starts -------------------------------
$ bugtest
1 2 3 44 66
c.e = 66
c.d = 44

5 2 3 44 66
c.a = 5
c.e = 66
c.d = 44
------- output ends ---------------------------------
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?





More information about the Python-list mailing list