Instantiate an object based on a variable name

W

Wells

Sorry, this is totally basic, but my Google-fu is failing:

I have a variable foo. I want to instantiate a class based on its
value- how can I do this?
 
M

Martin P. Hellwig

Wells said:
Sorry, this is totally basic, but my Google-fu is failing:

I have a variable foo. I want to instantiate a class based on its
value- how can I do this?

My crystal ball is failing too, could you please elaborate on what
exactly you want to do, some pseudo code with the intended result will
be fine.
 
D

Diez B. Roggisch

Wells said:
Sorry, this is totally basic, but my Google-fu is failing:

I have a variable foo. I want to instantiate a class based on its
value- how can I do this?


class Foo(object):
pass


ze_class = Foo

f = ze_class()


Diez
 
S

Steven D'Aprano

Sorry, this is totally basic, but my Google-fu is failing:

I have a variable foo. I want to instantiate a class based on its value-
how can I do this?

The right way to do it is like this:

.... pass
....<__main__.C instance at 0xb7ce60ec>


Many newbies don't think of that, because they're not used to classes
being first-class objects like strings, floats, ints and similar. It's a
very useful technique when you want to do something to a whole lot of
different classes:

for theclass in [MyClass, C, Klass, int, str, SomethingElse]:
process(theclass())


Here's an alternative, for those times you only have the name of the
class (perhaps because you've read it from a config file):

foo = "C" # the name of the class
actual_class = globals()[foo]
instance = actual_class()
instance
<__main__.C instance at 0xb7ce608c>


The obvious variation if the class belongs to another module is to use
getattr(module, foo) instead of globals()[foo].
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,059
Members
48,769
Latest member
Clifft

Latest Threads

Top