Author: techfox9
Python dynamic class loading ..
Saturday, October 16th, 2010 @ 12:16 pm
File “mod_loader.py” :
# file: mod_loader.py mod_name = "pkg.mod_loadee" # Get module object (class is stored in a module) mod_obj = __import__(mod_name, globals(), locals(), ['']) print ">> %s" % mod_obj # Get class class_obj = mod_obj.getClass() print ">> %s" % class_obj # Create instance from class object class_inst = class_obj() # invoke method class_inst.testme()
in folder “pkg”, make file “mod_loadee.py” :
class Loadee: def __init__(self): print "Loadee.init" def testme(self): print "Loadee.testme" def getClass(): return Loadee
run it:
python mod_loader.py
do not forget the “./pkg/__init__.py” to make the folder a package .
.