[Tutor] Creating an object with a string

Roeland Rengelink roeland.rengelink at chello.nl
Mon May 24 05:07:40 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?
>
The canonical way to do this with Python is to create a dictionary that 
maps strings to classes. E.g:

class A:
    ...

class B:
    ...

cls_map = {'A': A, 'B':B}

def create_class(a_string):
    return cls_map[a_string]()

If your strings match the class names then you could use eval()

instance = eval(a_string+"()")

Hope this helps,

Roeland





More information about the Tutor mailing list