How to create an object instance from a string??

Peter Hansen peter at engcorp.com
Sun Mar 20 04:29:17 CET 2005


Do Re Mi chel La Si Do wrote:
> Also :
>     classname = "Dog"
>     exec("b="+classname+"()")
>     b.bark()
> 
> or
>     classname = "Dog"
>     exec("cl="+classname)
>     b=cl()
>     b.bark()

Ugh.

The statement exec (note: it's a statement, not a
function call as you imply with the above) is rarely
either required or good style.

In this case it's neither.

-Peter



More information about the Python-list mailing list