Say i have a class:
class Foo(object):
def __init__(self,d):
self.d=d
d={'a':1,'b':2}
inst=Foo(d)
inst.d
Out[315]: {'a': 1, 'b': 2}
Is there a way to dyamically create n attributes where each attribute would be a dict key, so inst.a
would return 1
and so on.
You could do something like this:
Here is a solution even more outlandish than the one offered by pythonm:
Instead of using
inst.d
, useinst.__dict__
directly. An added benefit is that new keys added tod
automatically become attributes. That's as dynamic as it gets.use
setattr()
:That would do it.
You can also use the
setattr
built-in method:You can also use
__getattr__
.