In article <[EMAIL PROTECTED]>,
Ben Finney  <[EMAIL PROTECTED]> wrote:
>"John" <[EMAIL PROTECTED]> 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'
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to