instantiate a class with a variable

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Mar 27 19:19:09 EST 2006


"John" <johnwadeunderwood at yahoo.com> writes:
> class foo:
>     def method(self):
>         pass
>
> x='foo'
>
> Can I use variable x value to create an instance of my class?

You seem to be asking "is it possible to call an object whose name is
stored in a string".

The answer is yes::

    >>> class Foo:
    ...     pass
    ...
    >>> foo_name = 'foo'
    >>> foo_class = locals().get(foo_name)
    >>> bar = foo_class()
    >>> bar
    <__main__.Foo instance at 0x401e468c>

Or, more succinctly but rather harder to follow::

    >>> class Foo:
    ...     pass
    ...
    >>> foo_name = 'foo'
    >>> bar = locals().get(foo_name)()
    >>> bar
    <__main__.Foo instance at 0x401e46ec>

-- 
 \     "I went to the cinema, it said 'Adults: $5.00, Children $2.50'. |
  `\       So I said 'Give me two boys and a girl.'"  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list