map -> class instance

Bengt Richter bokr at oz.net
Wed Jun 12 19:45:01 EDT 2002


On Wed, 12 Jun 2002 16:49:32 -0500, John Hunter <jdhunter at nitace.bsd.uchicago.edu> wrote:

>
>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
>
>But got an infinite recursion:
>
>~/python/test $ python map_to_class.py 
>Traceback (most recent call last):
>  File "map_to_class.py", line 20, in ?
>    c = Map2Class(m)
>  File "map_to_class.py", line 3, in __init__
>    self.m = m
>  File "map_to_class.py", line 8, in __setattr__
>    self.m[key] = val
>  File "map_to_class.py", line 5, in __getattr__
>    return self.m[key]
>  File "map_to_class.py", line 5, in __getattr__
>    return self.m[key]
>        [snip ... lots more line fivers ]
>
>Is there a better/right way to do what I want?
>
This seems to work. I'm using 2.2:

 >>> def makeM2C(m):
 ...     class PersInf:
 ...         def __repr__(self):
 ...             return '<%s: "%s" "%s" %s" instance at %s>' % (
 ...                 self.__class__.__name__,self.first, self.last, self.age, id(self)
 ...             )
 ...     PersInf.__dict__.update(m)
 ...     return PersInf()
 ...
 >>> makeM2C(m)
 <PersInf: "John" "Hunter" 34" instance at 8208688>

I assume you're only interested in a single instance here, but if
you want to define an __init__ for PersInf, you can, and then return
Persinf instead of the instance PersInf(). You could then store the
returned class like AClass = makeM2C(aDict), and then do anInst = AClass(initparams).

But here it's one instance, with a few variations on feeding the factory a dictionary:
(You can just put pass where I defined __repr__ if you don't care)

 >>> c = makeM2C(m)
 >>> print c.first, c.last, c.age
 John Hunter 34
 >>> c2 = makeM2C({'first':'Ratoncito','last':'Miguel','age':'??'})
 >>> c2
 <PersInf: "Ratoncito" "Miguel" ??" instance at 8208416>
 >>> print c2.first, c2.last, c2.age
 Ratoncito Miguel ??
 >>> oi = 'Kalle Anka (gammal)'.split()
 >>> c3 = makeM2C(dict(zip(['first','last','age'],oi))
 ... )
 >>> c3 = makeM2C(dict(zip(['first','last','age'],oi)))
 >>> c3
 <PersInf: "Kalle" "Anka" (gammal)" instance at 8192544>
 >>> print c3.first, c3.last, c3.age
 Kalle Anka (gammal)
 
HTH

Regards,
Bengt Richter



More information about the Python-list mailing list