Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Instantiate an object based on a variable name

0 views
Skip to first unread message

Wells

unread,
Dec 31, 2009, 11:54:57 AM12/31/09
to
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?

Martin P. Hellwig

unread,
Dec 31, 2009, 12:04:11 PM12/31/09
to

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.'

Diez B. Roggisch

unread,
Dec 31, 2009, 12:05:46 PM12/31/09
to
Wells schrieb:

> 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

Steven D'Aprano

unread,
Dec 31, 2009, 12:06:11 PM12/31/09
to

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

0 new messages