1

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?

1
  • 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 stackoverflow.com/questions/285061/… ? Commented Jan 22, 2016 at 23:08

2 Answers 2

3

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

3 Comments

You could do setattr(foo, "bar", 42) instead of manually altering the instance's __dict__
Actually, setting the __dict__ doesn't work (at least not in Pyhton 3). setattr works fine though.
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.
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

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.