Adding a 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 code above does not work. Any suggestion?

+3
source share
3 answers

The easiest way to fill one with the dictother is the methodupdate() , so if you expand objectto provide an object has __dict__, you can try something like this:

>>> class Site(object):
...     pass
...
>>> site = Site()
>>> site.__dict__.update(dict)
>>> site.a

Or perhaps even:

>>> class Site(object):
...     def __init__(self,dict):
...         self.__dict__.update(dict)
...
>>> site = Site(dict)
>>> site.a
+7
source

As said in , it object()returns a faceless object, that is, it cannot have any attributes. He does not have __dict__.

What you can do is the following:

>>> site = type('A', (object,), {'a': 42})
>>> site.a
42
+6
source
class site(object):
    pass
for k,v in dict.iteritems():
    setattr(site,k,v)
print site.a #it does works
+1
source

Source: https://habr.com/ru/post/1768414/


All Articles