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.
asked Oct 9, 2012 at 18:59
root
81.2k25 gold badges111 silver badges120 bronze badges
5 Answers 5
class Foo(object):
def __init__(self, attributes):
self.__dict__.update(attributes)
That would do it.
>>>foo = Foo({'a': 42, 'b': 999})
>>>foo.a
42
>>>foo.b
999
You can also use the setattr built-in method:
class Foo(object):
def __init__(self, attributes):
for attr, value in attributes.iteritems():
setattr(self, attr, value)
answered Oct 9, 2012 at 19:09
unddoch
6,0421 gold badge28 silver badges39 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
use setattr():
>>> class foo(object):
def __init__(self, d):
self.d = d
for x in self.d:
setattr(self, x, self.d[x])
>>> d = {'a': 1, 'b': 2}
>>> l = foo(d)
>>> l.d
{'a': 1, 'b': 2}
>>> l.a
1
>>> l.b
2
>>>
phant0m
17k6 gold badges52 silver badges84 bronze badges
answered Oct 9, 2012 at 19:09
Ashwini Chaudhary
252k60 gold badges479 silver badges520 bronze badges
1 Comment
Ashwini Chaudhary
@root yes, just move the for-loop inside the
__init__().see the edited solution.Here is a solution even more outlandish than the one offered by pythonm:
class Foo(object):
def __init__(self, d):
self.__dict__ = d
Instead of using inst.d, use inst.__dict__ directly. An added benefit is that new keys added to d automatically become attributes. That's as dynamic as it gets.
answered Oct 9, 2012 at 19:29
user4815162342
159k22 gold badges351 silver badges419 bronze badges
Comments
You could do something like this:
class Foo(object):
def __init__(self, **kwdargs):
self.__dict__.update(kwdargs)
d = {'a':1,'b':2}
foo = Foo(**d)
foo2 = Foo(a=1, b=2)
answered Oct 9, 2012 at 20:53
martineau
124k29 gold badges181 silver badges319 bronze badges
Comments
You can also use __getattr__.
class Foo(object):
def __init__(self, d):
self.d = d
def __getattr__(self, name):
return self.d[name]
answered Oct 9, 2012 at 20:57
Niklas R
17k30 gold badges113 silver badges212 bronze badges
Comments
lang-py
inst.0is illegal syntax.__getitem__and friends.