mlzboy
mlzboy

Reputation: 14721

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?

Upvotes: 3

Views: 7771

Answers (3)

David Webb
David Webb

Reputation: 193814

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

Upvotes: 7

SilentGhost
SilentGhost

Reputation: 320039

As docs say, object() returns featureless object, meaning it cannot have any attributes. It doesn't have __dict__.

What you could do is the following:

>>> site = type('A', (object,), {'a': 42})
>>> site.a
42

Upvotes: 5

leoluk
leoluk

Reputation: 12981

class site(object):
    pass
for k,v in dict.iteritems():
    setattr(site,k,v)
print site.a #it does works

Upvotes: 1

Related Questions