[Tutor] Creating an object with a string

Martin Hjort Eriksen martin at hardcoder.dk
Mon May 24 05:26:53 EDT 2004

> 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

This helped...thank you very much...

A second question in the same area, again the start point is PHP, where 
you have variable variables. I have also looked through the Python 
litterature, and cannot find anything that helps.

The problem is, as I instantiate the objects, I will put them in an 
dictionary, where I have 4 dictionaries, one for each type of class. 
Since I have mulitple instances if the classes, I have added copy to the 
above code that Roeland sent. Based on that string I want to insert it 
into the correct dictionary, without using if many if sentences. PHP 
example again:

$foo = array();
$type = "foo";
$objectToInsert = new bar();

$$type[] = $objectToInsert;


More information about the Tutor mailing list