1

I'm trying to instantiate a class object whose desired name is held in a variable that's created elsewhere.

I can't figure out how to make the instance of the class have the name held by the variable.

example:

class foo: def __init__(self): self.var1 = "bar" if __name__ == "__main__": test = "a" # returned by another func. [string held by variable 'test'] = foo() print a.var1 

Is this possible? (or even advisable...)

2 Answers 2

2

It is not advisable, since it makes it difficult to program with the variable a when you do not know its name until run-time.

You might think about using a dict instead:

data = {} test = func() # "a" data[test] = foo() 
Sign up to request clarification or add additional context in comments.

1 Comment

I was just running into that problem as I then thought about what I then wanted to do next with the class functions... hmmm. Time to re-think. Thank you.
0

A function is probably better - that way the work you need to do is encapsulated and can be re-used:

def do_work(an_instance_of_foo): print an_instance_of_foo.var1 class foo: def __init__(self): self.var1 = "bar" if __name__ == "__main__": do_work(foo()) 

If you also need the word, you can pass it to the function:

def do_work(an_instance_of_foo, my_word): # etc. 

Alternately, you can use a dictionary as a namespace (as @unutbu has suggested) if you need the instance of foo to be associated with a particular name.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.