How to create an object instance from a string??

Peter Hansen peter at engcorp.com
Sat Mar 19 22:29:17 EST 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