instantiate a class with a variable

Cameron Laird claird at lairds.us
Mon Mar 27 21:08:02 EST 2006


In article <mailman.3742.1143505181.27775.python-list at python.org>,
Ben Finney  <bignose+hates-spam at benfinney.id.au> wrote:
>"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 hope few are so unwary as not to detect the apparent typographical
error
  foo_name = 'foo'
for
  foo_name = 'Foo'



More information about the Python-list mailing list