Reflectiong capabilityof Python

MRAB google at mrabarnett.plus.com
Wed Nov 26 03:55:11 CET 2008


goatold at gmail.com wrote:
> Can Python create object by name? Like
> clsName = "ClassA"
> aObj = createObjectByName(clsName)
 >
 >>> # Create the class.
 >>> class MyClass:
	pass

 >>> # The class is in the globals() dict.
 >>> globals()["MyClass"]
<class __main__.MyClass at 0x00D133F0>
 >>> # And also the locals() dict.
 >>> locals()["MyClass"]
<class __main__.MyClass at 0x00D133F0>
 >>> # Create an instance via the globals() dict.
 >>> globals()["MyClass"]()
<__main__.MyClass instance at 0x00D11530>
 >>> # Or via the locals() dict.
 >>> locals()["MyClass"]()
<__main__.MyClass instance at 0x00D15918>
 >>>



More information about the Python-list mailing list