[Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears
Bob Gailer
bgailer at alum.rpi.edu
Sat Oct 7 06:03:20 CEST 2006
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. As soon as I redefine my
> class to no longer inherit from Python dictionary, then I get expected
> behavior, but now I don't have benefit of Python dictionary methods
> such as pop and has_key:
>
> sdso = Data_Set({'full_name':'full_name_obj',
> 'address_line_1':'address_line_1_obj'})
> >>> sdso
> {}
> >>> class Data_Set:
> def __init__(self, dict_of_datum, required=None):
> self.keys = dict_of_datum.keys
> self.values = dict_of_datum.values
> self.items = dict_of_datum.items
> self.required = required
>
>
> >>> sdso = Data_Set({'full_name':'full_name_obj',
> 'address_line_1':'address_line_1_obj'})
> >>> sdso
> <__main__.Data_Set instance at 0x419690ac>
> >>> sdso.keys()
> ['full_name', 'address_line_1']
> >>> sdso.pop('full_name')
>
> Traceback (most recent call last):
> File "<pyshell#311>", line 1, in -toplevel-
> sdso.pop('full_name')
> AttributeError: Data_Set instance has no attribute 'pop'
>
> 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).
--
Bob Gailer
just up the road in El Cerrito
510-978-4454
More information about the Tutor
mailing list