[Tutor] Re: Creating an object with a string
Riccardo Lemmi
riccardo at reflab.it
Mon May 24 10:26:44 EDT 2004
Martin Hjort Eriksen wrote:
> I am parsing an XML file, and based on certain tags, i want to create
> certain objects. During the parsing i generate a string, with which i
> determine what type of object I want to create. The simple way is to
> have som if statements to determine it, but I was wondering if there is
> not a more "smart" method. I also do lot of PHP programming, where it is
> possible to do:
>
> <?php
> $object = "ClassToCreate";
>
> $newObject = new $object();
>
> ?>
>
> In that way I am able to with very few lines, to create an object based
> on a string. Is there any way of doing something similar in Python?
>
> regards
>
> Martin Hjort Eriksen
>
>From shell:
>>> class ClassToCreate:
... pass
...
>>> newObject = globals()['ClassToCreate']()
>>> newObject
<__main__.ClassToCreate instance at 0x4029e98c>
>>>
If you use a module, for example:
>>> import UserDict
>>> ClassToCreate = getattr(UserDict,'UserDict')
>>> x=ClassToCreate()
>>> x
{}
>>>
--
Riccardo Lemmi
More information about the Tutor
mailing list