[Tutor] Mapping to object attributes

John Fouhy john at fouhy.net
Tue Oct 31 23:44:57 CET 2006


On 01/11/06, Mike Hansen <mhansen at cso.atmel.com> wrote:
> form = cgi.FieldStorage()
> widget = Widget()
>
> form_field_object_map = {'widget_name' : widget.name,
>                          'alt_widget_name' : widget.alt_name,
>                                  ...}
>
> for form_field in form_field_object_map.keys():
>     form_field_object_map[form_field]...er....

This won't work, because python will look up widget.name and replace
it with the value of widget.name when it creates the dictionary.

You can probably do something with setattr.  Check the docs for
details, but basically,
   setattr(thing, 'foo', 'bar')
is equivalent to
   thing.foo = 'bar'

eg:

form_field_object_map = { 'widget_name':'name',
'alt_widget_name':'alt_name', } # etc

form = cgi.FieldStorage()
widget = Widget()

for form_field in form_field_object_map:
    setattr(widget, form_field_object_map[form_field],
form.getvalue(form_field))

HTH!

-- 
John.


More information about the Tutor mailing list