How to create an object instance from a string??

Peter Hansen peter at engcorp.com
Sat Mar 19 17:41:34 EST 2005


Tian wrote:
> How can I create an instance of an object from a string?
> 
> For example, I have a class Dog:
> class Dog:
>   def bark(self):
>     print "Arf!!!"
> 
> 
> I have a string:
> classname = "Dog"
> 
> How can I create a instance of Dog from classname?
> Is there any such methods like those in Java?

You generally get a reference to the class object
(i.e. to Dog) using either globals(), locals(),
or getattr() as appropriate for the specific
situation at hand...

-Peter



More information about the Python-list mailing list