[Tutor] passing form data into a class
Kent Johnson
kent37 at tds.net
Tue Jul 31 13:44:47 CEST 2007
tpc247 at gmail.com wrote:
> dear fellow Python enthusiasts, let's say I have a dictionary of keys
> and values obtained from a form submitted by a user. For each submitted
> form I will create the Application and Candidate classes, and I want to
> be able to call Application(Candidate(**submitted_data)).display() to
> create an html representation of the user submitted data. Depending on
> the applicant's preferences and location, the number of fields on the
> form, and thus the size of this dictionary, is variable, and not all
> fields are required. I seem to recall a setargs function in Python that
> would take any argument passed into a class and set that argument as a
> member variable in a class. A Google search turned up no such
> construct, so here I am asking you, 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 ?
I occasionally find this handy:
class Bunch(object):
''' A container for data that supports attribute access.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308
'''
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __repr__(self):
state = ["\n %s=%r" % (attribute, value)
for (attribute, value)
in sorted(self.__dict__.items())]
return self.__class__.__name__ + ':' + ''.join(state)
Kent
More information about the Tutor
mailing list