map -> class instance

Benno benjl at cse.unsw.edu.au
Thu Jun 13 01:15:52 EDT 2002


John Hunter <jdhunter at nitace.bsd.uchicago.edu> wrote in message news:<m2r8jcp3pv.fsf at video.paradise.lost>...
> I want to convert dictionary instances to instances of a class that
> has the keys of the map as attributes.  I naively tried this:
> 
> class Map2Class:
>     def __init__(self,m):
>         self.m = m
> 
>     def __getattr__(self, key):
>         return self.m[key]
> 
>     def __setattr__(self, key, val):
>         self.m[key] = val
> 
>     def __delattr__(self, key):
>         if self.m.has_key(key):
>             del self.m[key]
> 
> m = {'first' : 'John',
>      'last' : 'Hunter',
>      'age' : 34}
> 
> c = Map2Class(m)
> print c.first, c.last, c.age

<snip>

Depending on the exact semantics that you require a much simpler way would be:

class Map2Class: 
    def __init__(self, dikt): 
        self.__dict__ = dikt 
 
 
dikt = {'first':'John', 'last':'Hunter', 'age':34} 
 
c = Map2Class(dikt) 
print c.first, c.last, c.age 
 

Cheers,

Benno



More information about the Python-list mailing list