tags:

views:

17

answers:

2

In a class inherited from dict, why don't the two ways of defining an attribute produce the same result? Why do I see attr1 but not attr2?

class my_dict(dict):
   def __init__(self):
       dict.__init__(self)
       self['attr1'] = 'seen'
       setattr(self, 'attr2', 'unseen')

In [1]: x = my_dict()

In [2]: x
Out[2]: {'attr1': 'seen'}
+1  A: 

For the same reason that:

x = {}
x.foo = 34

doesn't work. dicts don't work by defining attributes.

Cory Petosky
+1  A: 
x.attr2
# => 'unseen'
grifaton