Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding dynamic property to a python object

site = object()
mydict = {'name': 'My Site', 'location': 'Zhengjiang'}
for key, value in mydict.iteritems():
    setattr(site, key, value)
print site.a  # it doesn't work

The above code didn't work. Any suggestion?

like image 570
mlzboy Avatar asked Jun 14 '26 11:06

mlzboy


1 Answers

The easiest way to populate one dict with another is the update() method, so if you extend object to ensure your object has a __dict__ you could try something like 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
like image 185
Dave Webb Avatar answered Jun 16 '26 03:06

Dave Webb