[Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears

Kent Johnson kent37 at tds.net
Sat Oct 7 14:46:07 CEST 2006

Bob Gailer wrote:
> tpc247 at gmail.com wrote:
>> hi all, I would like to create a class that specializes Python 
>> dictionary.  I would like an instance of this class to store objects 
>> representing html form data, and I would like to have an instance of 
>> this Data_Set class be able to use the Python dictionary method pop to 
>> remove objects as I see fit.  I defined the following:
>> class Data_Set(dict):
>>     def __init__(self, dict_of_datum_objects, required=None):
>>         self.keys = dict_of_datum_objects.keys
>>         self.values = dict_of_datum_objects.values
>>         self.required = required
>> For some reason, whenever I create an instance of this class with 
>> data, all I get is an empty dictionary. 

>> Am I doing something wrong ?
> Err, yes. You are assuming that assigning to self.keys and self.values 
> creates dictionary entries. All that actually does is assign the 2 lists 
> to 2 attributes.
> Try instead self.update(dict_of_datum_objects).

In general, when you create a subclass, the subclass __init__() method 
should call the base class __init__(). Otherwise the base class is not 
initialized. That is what you see - you get an empty dict.

The syntax for the call to the base class __init__() is a little 
strange, it looks like this:
   base.__init__(self, args)
where base is the name of the base class and args are the arguments for 
the base class __init__() method.

As Bob points out, you are also making unwarranted assumptions about the 
way dict stores its data.

Try this:
     def __init__(self, dict_of_datum_objects, required=None):
         dict.__init__(self, dict_of_datum_objects)
         self.required = required


More information about the Tutor mailing list