Class initialization from a dictionary, how best?

Bengt Richter bokr at oz.net
Fri Jan 14 15:42:11 CET 2005


On 13 Jan 2005 20:36:19 -0800, "brianobush at gmail.com" <brianobush at gmail.com> wrote:

>#
># My problem is that I want to create a
># class, but the variables aren't known
># all at once. So, I use a dictionary to
># store the values in temporarily.
Why?
># Then when I have a complete set, I want to
># init a class from that dictionary.
Why do it that way?

># However, I don't want to specify the
># dictionary gets by hand
># since it is error prone.
># Thanks for any ideas, Brian
>
>
>  So I have a class defined that accepts a number of variables
># and they must be all present at object creation time.
Why? Why not a method to check if it's valid yet, and then
add the attributes as they're available, without intermediaries.
You can make Test "smart" so it won't accept any other names than a,b,c
and will automatically convert to str, str, and int. Etc.

What are you actually doing? Is this a toy example of a more complex class?

>class Test:
>def __init__(self, a, b, c):
>self.a = a
>self.b = b
>self.c = c
>def __str__(self):
>return '%s, %s, %d' % (self.a, self.b, self.c)
>
># For example:
>t1 = Test('asd', 'sdf', 9)
>print t1
>
># However, due to parsing XML, I am
># creating the values incrementally
># and I want to store them in a dictionary
># and then map them easily to a class
Why store them in a dictionary? Why not create an empty Test instance,
and incrementally add the attributes directly as they're available?

What are you going to do with t1 and other instances?

>
>dictionary = {}
>
># a mapping from source to destination
>mapping = {
>'a': str,
>'b': str,
>'c': int,
>}
>
># a sample source of values
>test_source = {
>'a': 'test',
>'b': 'asdf',
>'c': 45
>}
>
># now we go through and extract the values
># from our source and build the dictionary
Just the three items in the test_source dictionary?
Is that just a 3-item holding place until you
>
>for attr_name, function in mapping.items():
>dictionary[attr_name] = function(test_source.get(attr_name))
>
>print dictionary
>
># Here is the problem I want to avoid:
># Having to list the variable names
># as strings in multiple places. It is enought to
># have them in the 'mapping'
># dictionary above
>
>t2 = Test(dictionary.get('a'), dictionary.get('b'),
>dictionary.get('c'))
>print t2
>
Why don't you just let Test do all the work, and update it incrementally
until it is complete. You can use descriptors to manage state. You could
do any number of things. The main problem is defining the _requirements_
without premature implementation, never mind premature optimization ;-)

You may have good reasons for wanting to do what you seem to want to do,
but the picture is not clear to me ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list