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设计模式之外观模式。分享给大家供大家参考,具体如下: 外观模式(Facade Pattern):为子系统中的一组接口提供一个一致界面,此模式定义一个高层接口,使...

python批量生成本地ip地址的方法

本文实例讲述了python批量生成本地ip地址的方法。分享给大家供大家参考。具体分析如下: 这段代码用于在本地计算机上生成本地ip地址绑定到网卡,生成的是一个bat的批处理文件,运行此批...

python3.6环境安装+pip环境配置教程图文详解

python3.6环境安装+pip环境配置教程图文详解

1、python安装可以跨平台 2、有两个版本2.7和3.6,第三方库适用2.7版,两个版本不兼容 windows安装: 第一种方法官网安装: 在官网下载安装包如图: 图下点击是默认下...

Python中字典创建、遍历、添加等实用操作技巧合集

字段是Python是字典中唯一的键-值类型,是Python中非常重要的数据结构,因其用哈希的方式存储数据,其复杂度为O(1),速度非常快。下面列出字典的常用的用途. 一、字典中常见方法列...

python读csv文件时指定行为表头或无表头的方法

python读csv文件时指定行为表头或无表头的方法

pd.read_csv()方法中header参数,默认为0,标签为0(即第1行)的行为表头。若设置为-1,则无表头。示例如下: (1)不设置header参数(默认)时: df1 =...