python基础-动态加载lazy

xiaoxiao2021-02-27  326

看了一天动态加载,普遍有这么几种方法,总结一下,由简入深,本文仅对查到的栗子们做个引用……省去你们大把查资料的时间= =

主要思想:把模块(文件)名、类名、方法名当成了变量 然后利用__import__和getattr实现调用。

注意下getattr()和__getattr__区别:

getattr():getattr(obj, “method”)(args)__getattr__:调用方法调用不到时,会调用当前类中的__getattr__方法,返回值或AttributeError异常

1、网上大多举栗子都是这么写的= =。。。

#file: lazy_import/module1.py class A(object): def aa(self): print "aa" def bb(self, i, j): return i+j #file: lazy_import/test1.py #coding=UTF-8 def main(): module_name = "module1" class_name = "A" method = "aa" imp_module = __import__(module_name) imp_class = getattr(imp_module, class_name) obj = imp_class() print "#module:", imp_module print "#class:", imp_class print "#obj:", obj imp_method = getattr(obj, method) print "#method:", imp_method imp_method() # call def, 与 imp_method = getattr(obj, method)一起作用,相当于obj.aa() imp_method_bb = getattr(obj, "bb") ret = imp_method_bb(1, 2) print "#ret:", ret if __name__ == '__main__': main() python lazy_import/test1.py #module: <module 'module1' from '/xxxxx/lazy_import/module1.pyc'> #class: <class 'module1.A'> #obj: <module1.A object at 0x107cf1710> #method: <bound method A.aa of <module1.A object at 0x107cf1710>> aa #ret: 3

2、还发现另外一个栗子这个博主原创

class LazyImport: def __init__(self, module_name): self.module_name = module_name self.module = None def __getattr__(self, funcname): if self.module is None: self.module = __import__(self.module_name) print(self.module) return getattr(self.module, funcname) a = LazyImport('string') print(a.lower("WEW")) #'wew'

3、还有这个栗子这个博主原创

#file: lazy_import/module2.py def test(s, e): print "in test func...", s, e class C(object): def __init__(self, name): print "in C class init...", name def cc(self): print 'in C class cc func' #file: lazy_import/test2.py class Dynload(object): def __init__(self, package): self.package = package def getobject(self): # return __import__(self.package, globals(), locals(), [], -1) return __import__(self.package) # import module def get_class_instance(self, class_name, *args): return getattr(self.getobject(), class_name)(*args) def get_class_func(self, instance, method, *args): return getattr(instance, method)(*args) def get_func(self, method, *args): return getattr(self.getobject(), method)(*args) if __name__ == '__main__': dyn = Dynload('module2') print "module=", dyn # module= <__main__.Dynload object at 0x10f450150> # 是一个Dynload对象 # 直接__import__(module2)时,会返回<module 'module2' from '/xxxxx/lazy_import/module2.pyc'> dyn.get_func('test', 'Hello', 'function!') ins = dyn.get_class_instance('C', 'Tom') dyn.get_class_func(ins, 'cc')
转载请注明原文地址: https://www.6miu.com/read-2085.html

最新回复(0)