On 19 Mar 2005 14:16:42 -0800, Tian <[EMAIL PROTECTED]> 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?

If class Dog is in the same namespace:
dog_class = globals()[classname]
dog = dog_class()
dog.bark()

If class is declared in another file, e.g. "animals.py":
import animals
dog_class = getattr(animals, classname)
dog = dog_class()
dog.bark()


-- 
Ksenia
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to