Instantiate an object based on a variable name
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Dec 31 12:06:11 EST 2009
On Thu, 31 Dec 2009 08:54:57 -0800, Wells wrote:
> 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:
>>> class C:
... pass
...
>>> foo = C # assign the class itself to the variable foo
>>> instance = foo()
>>> instance
<__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].
--
Steven
More information about the Python-list
mailing list