[Tutor] passing form data into a class

Dave Kuhlman dkuhlman at rexx.com
Tue Jul 31 18:09:46 CEST 2007


On Mon, Jul 30, 2007 at 08:32:55PM -0700, 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 ?
> The current way I do this is with a very long argument list, and line by
> line:

You have already gotten one good solution from Kent.  But,
depending on your needs, you might also focus on the request side
rather than on when the class or instance is created.  That might
enable you to add a bit of the security checking that Ken Fouey was
concerned about.

Here is an example of a class which looks a name up in a dictionary
when the attribute is requested.  It does not create attributes for
the keys in the dictionary:

    class Bunch(object):
        def __init__(self, vardict=None):
            if vardict is None:
                self.vardict = vardict
            else:
                self.vardict = vardict
        def __getattr__(self, name):
            if name in self.vardict:
                return self.vardict[name]
            else:
                raise AttributeError, 'Bunch has no attribute: %s' % name

    def test():
        d = {'aaa': 111, 'bbb': 222, }
        b = Bunch(d)
        print b.aaa
        print b.ccc

    test()

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list