Adding dynamic property to a python object -
site = object() mydict = {'name': 'my site', 'location': 'zhengjiang'} key, value in mydict.iteritems(): setattr(site, key, value) print site.a # doesn't work
the above code didn't work. suggestion?
the easiest way populate 1 dict
the update()
method, if extend object
ensure object has __dict__
try this:
>>> class site(object): ... pass ... >>> site = site() >>> site.__dict__.update(dict) >>> site.a
or possibly even:
>>> class site(object): ... def __init__(self,dict): ... self.__dict__.update(dict) ... >>> site = site(dict) >>> site.a
Comments
Post a Comment