The examples in this article describe the reflection usage in Python. Share to everyone for your reference. as follows:
Import sys, types,new def _get_mod (modulepath): Try:amod = Sys.modules[modulepath] If not isinstance (Amod, Typ Es.
Moduletype): Raise Keyerror except Keyerror: # The last ['] is very important! Amod = __import__ (Modulepath, Globals (), locals (), [']) sys.modules[modulepath] = amod return amod def _get_func (fu
Llfuncname): "" "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
, FuncName) # Assert that this function is a *callable* attribute. Assert callable (Afunc), U "%s is not callable."% Fullfuncname # return a reference to the function itself, # not the R
Esults of the function.
Return Afunc def _get_class (FullClassName, Parentclass=none): "" "The 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 are 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 is not a subclass of%s
"% (FullClassName, ParentClass)") # Return a reference to the class itself, not a instantiated object. Return AClass def applyfuc (obj,strfunc,arrargs): Objfunc = GetAttr (obj, strfunc) return apply (Objfunc,arrargs) def ge TObject (fullclassname): Clazz = _get_class (fullclassname) return Clazz () if __name__== ' __main__ ': Aa=getobject ("inet Services.services.company.Company ") bb=applyfuc (AA," select ", [' SELECT * from Ngsys2 ', None]) print BB
I hope this article will help you with your Python programming.