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.
--
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'
class Foo(object):
pass
ze_class = Foo
f = ze_class()
Diez
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