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

Posted in 未分类

发表评论