[Tutor] How do I make a variable that refers to an object have thesame label as the object's name ?
Alan Gauld
alan.gauld at btinternet.com
Thu Oct 5 11:38:22 CEST 2006
> when creating a series of objects, where each object represents a
> field from
> a submitted html form, how do I make variables that reference the
> objects be
> the same as the names of the respective objects ?
The usual solution for this is to use a dictionary keyed by object
name.
There is an example of this technique in my OOP topic in my tutor
using bank accounts keyed by account number - under the heading
"Collections of Objects".
There are other solutions based on modifying the global namerspace
but thats messy IMHO and makes your code very dependant on the
pre-knowledge of the fields passed which can introduce maintenance
problems later.
Using a dictionary your code becomes:
> class Datum:
> def __init__(self, value, required=None, label=None):
> self.value = value
> self.required = required
> self.label = label
>
> and a dictionary of submitted values:
>
> some_dict = {'applicant_full_name':'John Smith',
> 'applicant_address_line_1':'100 Main Street',
> 'applicant_city':'Anytown',
> 'applicant_state':'WY', 'applicant_postal_code':'55555',
> 'country':'US', '
> applicant_email':'jsmith at server.gov', 'applicant_telephone':'555 555
> 5555'}
>
> and I created a list of objects like so:
>
> some_list = {}
> for key, value in some_dict.items():
> some_list[key] = Datum(value)
> to make it so I can refer to each respective Datum instance by its
> Datum.key,
> e.g., applicant_full_name would refer to the Datum instance with key
> 'applicant_full_name' and applicant_full_name.value would give me
> "John
> Smith." I tried:
print some_list['applicant_full_name'].value
> for x in some_list:
> some_string = "%s = %s" % (x.key, x)
> eval(some_string)
You would need exec() not eval but...
eval and exec both have serious security implications and should
be avoided where possible. Hopefully the dictionary technique achieves
what you want?
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list