0

I want to create an object (say foo) with dynamically created attributes. I can do something like this:

class Foo:
    pass

foo.bar = 42
...
print(foo.bar) # 42

However, when I create the attribute, I don't know the name of the attribute yet. What I need is something like this:

def createFoo(attributeName):
    foo = ???
    ??? = 42

...

foo = createFoo("bar")
print(foo.bar) # 42

How can I achieve this?

petersohn
  • 11,292
  • 13
  • 61
  • 98
  • 1
    I didn't quite understand. inside the function, `foo = ???` is creating the instance? (e.g. `foo = Foo()`). And the value (42), where does that come from? How come it is not also passed as an argument to `createFoo` ? Isn't this question a duplicate of http://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute-in-python ? – CristiFati Jan 22 '16 at 23:08

2 Answers2

2

setattr:

class Foo:
    pass

foo = Foo()
setattr(foo, 'bar', 42)
print(foo.bar)  # 42

Or, as I originally answered before shmee suggested setattr:

foo = Foo()
foo.__dict__['man'] = 3.14
print(foo.man)  # 3.14
hansmosh
  • 491
  • 5
  • 13
  • 3
    You could do `setattr(foo, "bar", 42)` instead of manually altering the instance's `__dict__` – shmee Jan 22 '16 at 23:10
  • Actually, setting the `__dict__` doesn't work (at least not in Pyhton 3). `setattr` works fine though. – petersohn Jan 24 '16 at 14:25
  • I am using Python 3 and `__dict__` works. What problem are you seeing? Even though it works, it really shouldn't be the preferred way to get this done anyway. – hansmosh Jan 25 '16 at 17:44
0

You could use a dictionary

then create a get function to easily access it

def createFoo(attributeName):
    dict[attributeName] = 42;

def GetVal(attributeName)
   return dict[attributeName];
...

foo = createFoo("bar")
print(foo.GetVal("bar")) # 42
Rosenumber14
  • 165
  • 12