python中反射用法实例

yipeiwu_com5年前Python基础

本文实例讲述了python中反射用法。分享给大家供大家参考。具体如下:

import sys, types,new
def _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 aMod
def _get_func(fullFuncName):
  """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 the function is a *callable* attribute.
  assert callable(aFunc), u"%s is not callable." % fullFuncName
  # Return a reference to the function itself,
  # not the results of the function.
  return aFunc
def _get_Class(fullClassName, parentClass=None):
  """Load a module and retrieve a class (NOT an 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 not 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 an instantiated object.
  return aClass
def applyFuc(obj,strFunc,arrArgs):
  objFunc = getattr(obj, strFunc)
  return apply(objFunc,arrArgs)
def getObject(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

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python写的一个定时重跑获取数据库数据

Python写的一个定时重跑获取数据库数据

做大数据的童鞋经常会写定时任务跑数据,由于任务之间的依赖(一般都是下游依赖上游的数据产出),所以经常会导致数据获取失败,因为很多人发现数据失败后 都会去查看日志,然后手动去执行自己的任务...

python中pip的安装与使用教程

python中pip的安装与使用教程

在安装pip前,请确认win系统中已经安装好了python,和easy_install工具,如果系统安装成功,easy_install在目录python的安装盘(如C盘):\Python...

python写入并获取剪切板内容的实例

写桌面程序或有些特殊操作的,经常需要访问剪切板。python有专用的模块,可以很方便简单的操作剪切板 如下: #coding:utf-8 import win32clipboard...

在Python中处理日期和时间的基本知识点整理汇总

在Python中处理日期和时间的基本知识点整理汇总

 Python程序可以处理多种方式的日期和时间。日期格式之间的转换是一种常见计算机的杂活。 Python的时间和日历模块,能帮助处理日期和时间。 Tick是什么? 时间...

django 使用全局搜索功能的实例详解

安装需要的包 1 第一步: 全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理。 haystack:全文检索的框架,支持whoosh、solr、Xap...