python中反射用法实例

yipeiwu_com6年前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示例:实现保存网页到本地复制代码 代码如下:#coding=utf-8__auther__ = 'xianbao'import urllibimport osdef re...

对python实现二维函数高次拟合的示例详解

在参加“数据挖掘”比赛中遇到了关于函数高次拟合的问题,然后就整理了一下源码,以便后期的学习与改进。 在本次“数据挖掘”比赛中感觉收获最大的还是对于神经网络的认识,在接近一周的时间里,研究...

跟老齐学Python之关于类的初步认识

在开始部分,请看官非常非常耐心地阅读下面几个枯燥的术语解释,本来这不符合本教程的风格,但是,请看官谅解,因为列位将来一定要阅读枯燥的东西的。这些枯燥的属于解释,均来自维基百科。 1、问题...

python 检查是否为中文字符串的方法

python 检查是否为中文字符串的方法

【目标需求】 查看某一个字符串是否为中文字符串 【解决办法】 def check_contain_chinese(check_str): for ch in check_str:...

Pytorch之contiguous的用法

contiguous tensor变量调用contiguous()函数会使tensor变量在内存中的存储变得连续。 contiguous():view只能用在contiguous的var...