[Python] python中使用反射的方法 →→→→→进入此内容的聊天室

来自 , 2020-08-14, 写在 Python, 查看 116 次.
URL http://www.code666.cn/view/6a7dc081
  1. import sys, types,new
  2.  
  3. def _get_mod(modulePath):
  4.     try:
  5.         aMod = sys.modules[modulePath]
  6.         if not isinstance(aMod, types.ModuleType):
  7.             raise KeyError
  8.     except KeyError:
  9.         # The last [''] is very important!
  10.         aMod = __import__(modulePath, globals(), locals(), [''])
  11.         sys.modules[modulePath] = aMod
  12.     return aMod
  13.  
  14. def _get_func(fullFuncName):
  15.     """Retrieve a function object from a full dotted-package name."""
  16.    
  17.     # Parse out the path, module, and function
  18.     lastDot = fullFuncName.rfind(u".")
  19.     funcName = fullFuncName[lastDot + 1:]
  20.     modPath = fullFuncName[:lastDot]
  21.    
  22.     aMod = _get_mod(modPath)
  23.     aFunc = getattr(aMod, funcName)
  24.    
  25.     # Assert that the function is a *callable* attribute.
  26.     assert callable(aFunc), u"%s is not callable." % fullFuncName
  27.    
  28.     # Return a reference to the function itself,
  29.     # not the results of the function.
  30.     return aFunc
  31.  
  32. def _get_Class(fullClassName, parentClass=None):
  33.     """Load a module and retrieve a class (NOT an instance).
  34.    
  35.    If the parentClass is supplied, className must be of parentClass
  36.    or a subclass of parentClass (or None is returned).
  37.    """
  38.     aClass = _get_func(fullClassName)
  39.    
  40.     # Assert that the class is a subclass of parentClass.
  41.     if parentClass is not None:
  42.         if not issubclass(aClass, parentClass):
  43.             raise TypeError(u"%s is not a subclass of %s" %
  44.                             (fullClassName, parentClass))
  45.    
  46.     # Return a reference to the class itself, not an instantiated object.
  47.     return aClass
  48.  
  49. def applyFuc(obj,strFunc,arrArgs):
  50.     objFunc = getattr(obj, strFunc)
  51.     return apply(objFunc,arrArgs)
  52.  
  53. def getObject(fullClassName):
  54.     clazz = _get_Class(fullClassName)
  55.     return clazz()
  56.  
  57. if __name__=='__main__':
  58.     aa=getObject("inetservices.services.company.Company")    
  59.     bb=applyFuc(aa, "select", ['select * from ngsys2',None])
  60.     print bb
  61.    
  62.  
  63. #//python/8459

回复 "python中使用反射的方法"

这儿你可以回复上面这条便签

captcha