[Tutor] passing form data into a class

John Fouhy john at fouhy.net
Tue Jul 31 06:27:59 CEST 2007


On 31/07/07, tpc247 at gmail.com <tpc247 at gmail.com> wrote:
> is there a way for me to create a class that accepts a dictionary of
> submitted data and uses each key ad value to create a corresponding member
> variable ?  The current way I do this is with a very long argument list, and
> line by line:
>
> class Candidate(object):
>     def __init__(self, full_name, address_line_1, city, postal_code, email,
> desired_program, telephone=None, disabled=None, can_receive_media=None,
> media_sent_to=None, ...):
>         self.full_name = full_name
>         self.address_line_1 = address_line_1
>         self.city = city
>         self.postal_code = postal_code
>         self.email = email
>         self.desired_program = desired_program

The setattr() function is probably what you remember.  You could write
something like:

  for var in ['full_name', 'address_line_1', 'city'] # etc
     setattr(self, var, locals()[var])

You could even write:

  for var in locals():
    setattr(self, var, locals()[var])

but what you gain in convienience you lose in clarity, and possibly
safety if you aren't careful..

-- 
John.


More information about the Tutor mailing list