Reflectiong capabilityof Python

Rafe rafesacks at
Wed Nov 26 05:54:37 CET 2008

On Nov 26, 9:18 am, goat... at wrote:
> Can Python create object by name? Like
> clsName = "ClassA"
> aObj = createObjectByName(clsName)

if you are talking about creating an objcet dynamically and naming the
CLASS name at runtime, use:
>>> obj = type("ClassA", object, {}) # The base class is object

If you know the name of the class and you want to get an instance
(object) of it dynamically, there are two ways I have found.

1)  use getattr(module, "Class A").

2) Use the globals() dict which is handy when you know the class is
always in the same module as the code that calls it (watch out for
inheritance across more than one module though. This can put the
globals() call in a different module.)

- Rafe

More information about the Python-list mailing list