Python 版 Instance Activator(python下载安装教程)

网友投稿 275 2022-09-05


Python 版 Instance Activator(python下载安装教程)

之前写一个Python 版本的DbRowFactory(链接),   在初始化DbRowFactory时候, 除了要传cursor外, 还需要传一个RowClass类, 还有一个RowClass类的模块名, 用起来不爽, 改造了一下. 这个事情的一个副产品Python 版 Intance Activator, 代码如下:

最新的代码和DbRowFactory都放在codeplex上了.

#! /usr/bin/env python#coding=utf-8import inspectimport sys__author__ = 'Harry Liu, '__date__ = '16 Feb 2012'__version__="0001"##reference doc##createIntance(full_class_name,*args,**kwargs):''' instantiate class dynamically [arguments] full_class_name: full class name that you want to instantiate, included package and module name if has *args: list style arguments in class constructor *kwargs: dict style arguments in class constructor [return] an instance of this full_class_name [example] import pyObjectCreator full_class_name="knightmade.logging.Logger" logger=pyObjectCreator.create_intance(full_class_name,'logname')''' class_meta=getClassMeta(full_class_name)if class_meta!=None: obj=class_meta(*args,**kwargs)else: obj=Nonereturn objdef getClassMeta(full_class_name): ''' get class meta object of full_class_name, then we can use this meta object to instantiate full_class_name [arguments] full_class_name: full class name that you want to instantiate, included package and module name if has [return] an instance of this full_class_name [example] import pyObjectCreator full_class_name="knightmade.logging.Logger" loggerMeta=pyObjectCreator.getClassMeta(full_class_name)''' namespace=full_class_name.strip().rsplit('.',1)if len(namespace)==1: class_name=namespace[0] class_meta=_getClassMetFromCurrModule(class_name)else: module_name=namespace[0] class_name=namespace[1] class_meta=_getClassMetaFromOtherModule(class_name,module_name)return class_metadef _getClassMetFromCurrModule(class_name): result=None module_name="__main__"for name, obj in inspect.getmembers(sys.modules[module_name]):if inspect.isclass(obj):if name==class_name: result=objbreakreturn resultdef _getClassMetaFromOtherModule(class_name, module_name): module_meta=__import__(module_name,globals(), locals(),[class_name])if module_meta!=None: class_meta=getattr(module_meta,class_name)else: class_meta=Nonereturn class_meta


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:近期需要学习的python资料
下一篇:dreampie--一个很不错的python命令行交互工具
相关文章

 发表评论

暂时没有评论,来抢沙发吧~