map -> class instance

John Hunter jdhunter at nitace.bsd.uchicago.edu
Wed Jun 12 23:49:32 CEST 2002


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?

Thanks,
John Hunter



More information about the Python-list mailing list