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程序设计有所帮助。

相关文章

Pandas时间序列重采样(resample)方法中closed、label的作用详解

Pandas提供了便捷的方式对时间序列进行重采样,根据时间粒度的变大或者变小分为降采样和升采样: 降采样:时间粒度变大。例如,原来是按天统计的数据,现在变成按周统计。降采样会涉及到...

人脸识别经典算法一 特征脸方法(Eigenface)

人脸识别经典算法一 特征脸方法(Eigenface)

这篇文章是撸主要介绍人脸识别经典方法的第一篇,后续会有其他方法更新。特征脸方法基本是将人脸识别推向真正可用的第一种方法,了解一下还是很有必要的。特征脸用到的理论基础PCA在另一篇博客里:...

python实现txt文件格式转换为arff格式

本文实例为大家分享了python实现txt文件格式转换为arff格式的具体代码,供大家参考,具体内容如下 将文件读取出来的时候默认都是字符型的,所以有转换出来有点问题,但是还是可以用的。...

Python实现读取文件最后n行的方法

本文实例讲述了Python实现读取文件最后n行的方法。分享给大家供大家参考,具体如下: # -*- coding:utf8-*- import os import time impo...

Django中几种重定向方法

这里使用的是django1.5 需求: 有一个界面A,其中有一个form B, 前台提交B之后,后台保存数据之后,返回界面A,如果保存失败需要在A界面提示错误。 这里就需要后台的重定向,...