知行编程网知行编程网  2022-11-02 22:00 知行编程网 隐藏边栏  11 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python中的反射怎么用?的相关知识,包括python映射函数,以及反射大师怎么用这些编程知识,希望对大家有参考作用。

在大多数语言中,都有反射机制。在功能上,反射是增加程序的动态描述能力。通俗地说,就是让用户参与代码执行的决策权。

如何在 Python 中使用反射?

在写程序的时候,我们会写很多类,而这些类有自己的函数、对象等等。这些类和函数服务于后续代码,程序员决定何时使用哪个类以及何时调用某个函数。但是很多时候,我们需要根据用户的需要来决定执行哪一段代码。用户可以通过点击、输入数据或其他方式发出指令,反射将用户的指令传递给需要执行的代码块。这个过程是自动执行的,不需要手动检查用户指令是否应该执行那段代码,但是反射机制会自动找到应该执行的代码块。大多数反射都是以web举例的,反射本身最常见的使用场景确实是根据web的url调用不同的函数。当然,在这里,我们不需要讨论他的具体应用,只是简单解释一下他的使用意义。

python的反射机制比较简单。有四个关键函数:getattr、hasattr、setattr 和 delattr。前两个是最常用的,最后一个是很少用的。 python本身定义的反射是指容器中某些元素在内存中的操作。这个容器不仅包括类,还包括函数和对象。三者的区别在于,在查找对象的时候,除了查找对象本身之外,还要去创建对象的类中查找。用实际例子来说明反射在python中的具体作用,我们先来看看需求。在所有语言中,我们都可以轻松地让用户自由输入数据,然后打印该数据,这是最简单的人机交互。代码中的实现过程是生成一个变量,获取用户输入的数据,赋值给变量。打印变量。同样,我们可以在一个类中定义两个函数,然后让用户输入数据,根据用户输入的数据决定执行哪个函数。这是一种人工反射机制。当只有两个函数要查找时,我们可以使用 if-else 来判断。但是如果有数百条数据,重复使用if不仅效率低下,而且代码量也无法估量。在这种情况下,需要反思。

本实例讲述了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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享