2

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.

3
  • 1
    Yes, but you wouldn't be able to use them because inst.0 is illegal syntax. Commented Oct 9, 2012 at 19:01
  • 2
    Yes, but why would you do that instead of accessing items by index, either straight from the list, or by overriding __getitem__ and friends. Commented Oct 9, 2012 at 19:04
  • @ delnan -- it's just an example, not a very practical solution, I would just like to learn how to dynamically create attributes. Commented Oct 9, 2012 at 19:09

5 Answers 5

3
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)
Sign up to request clarification or add additional context in comments.

Comments

2

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
>>> 

1 Comment

@root yes, just move the for-loop inside the __init__().see the edited solution.
1

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.

Comments

0

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)

Comments

0

You can also use __getattr__.

class Foo(object):

    def __init__(self, d):
        self.d = d

    def __getattr__(self, name):
        return self.d[name]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.