This example describes the reflection usage in Python. Share to everyone for your reference. Specific as follows:
Import sys, types,newdef _get_mod (modulepath): Try:amod = Sys.modules[modulepath] If not isinstance (AMod, types. Moduletype): Raise Keyerror except Keyerror: # The last ["] is very important! AMod = __import__ (Modulepath, Globals (), locals (), ["]) Sys.modules[modulepath] = AMod return amoddef _get_func (FULLF UNCName): "" "Retrieve a function object from a full dotted-package name." " # Parse out the path, module, and function Lastdot = Fullfuncname.rfind (U ".") FuncName = Fullfuncname[lastdot + 1:] Modpath = Fullfuncname[:lastdot] AMod = _get_mod (modpath) Afunc = GetAttr (AMod, F UNCName) # Assert The function is a *callable* attribute. Assert callable (Afunc), U '%s is not callable. '% Fullfuncname # Return A reference to the function itself, # not the Res Ults of the function. Return afuncdef _get_class (FullClassName, Parentclass=none): "" "Load a module and retrieve a Class (not a instance). If the ParentClass is supplied, className must be of parEntclass or a subclass of ParentClass (or None is returned). "" "AClass = _get_func (fullclassname) # Assert that the class is a subclass of ParentClass. If ParentClass is isn't none:if not Issubclass (AClass, ParentClass): Raise TypeError (U "%s was not a subclass of%s" % (FullClassName, ParentClass)) # Return A reference to the class itself, not a instantiated object. Return aclassdef Applyfuc (obj,strfunc,arrargs): Objfunc = GetAttr (obj, strfunc) return apply (Objfunc,arrargs) def getobj ECT (fullclassname): Clazz = _get_class (fullclassname) return Clazz () if __name__== ' __main__ ': Aa=getobject (" Inetservices.services.company.Company ") bb=applyfuc (AA," select ", [' SELECT * from Ngsys2 ', None]) print BB
Hopefully this article will help you with Python programming.