map -> class instance
Christophe Delord
christophe.delord at free.fr
Wed Jun 12 18:27:37 EDT 2002
self.x=y is a call to self.__setattr__, so if you write self.x=y in __setattr__ it is an infinite recursion.
(see http://www.python.org/doc/current/ref/attribute-access.html#l2h-112)
in __setattr__, self.m[key]=val may be written self.__dict__['m'][key]=val
in __init__, self.m=m may be written self.__dict__['m']=m
$ cat map2class.py
class Map2Class:
def __init__(self,m):
self.__dict__['m'] = m
def __getattr__(self, key):
return self.m[key]
def __setattr__(self, key, val):
self.__dict__['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
$ python map2class.py
John Hunter 34
$
Christophe.
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?
>
> Thanks,
> John Hunter
--
(o_ Christophe Delord _o)
//\ http://christophe.delord.free.fr/ /\\
V_/_ mailto:christophe.delord at free.fr _\_V
More information about the Python-list
mailing list