Python动态加载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dutsoft/article/details/52054347

动态加载模块和类

方式1:系统函数import()
方式2:imp, importlib 模块
方式3:exec 函数

module.py

class Hello:
    def test(self):
        print "test"

    int_value = 123456
    str_value = "a python string"

if __name__ == '__main__':
    print __file__, __name__

import_module.py

#!/usr/bin/python
#coding: utf-8

import importlib


def f1():
    """
    使用__import__来实现动态加载
    """
    module_name = "module"
    module1 = __import__(module_name)
    h = module1.Hello()
    h.test()


def f2():
    """
    使用importlib
    importlib相比__import__(),操作更简单、灵活,支持reload()
    """
    module_name = "module"
    class_name = "Hello"
    test_module = importlib.import_module(module_name)
    # 使用getattr()获取模块中的类
    test_class = getattr(test_module, class_name)
    # 动态加载类test_class生成类对象
    test_obj = test_class()
    test_obj.test()


    # reload()重新加载,一般用于原模块有变化等特殊情况。
    reload_module = importlib.import_module(module_name)
    print(getattr(reload_module, class_name).int_value)
    print(getattr(reload_module, class_name).str_value)



if __name__ == '__main__':
    f1()
    f2()

运行结果:

$ python import_module.py 
test
test
123456
a python string

动态加载方法

import_func.py

#!/usr/bin/python
#coding: utf-8

# normal method
def test():
    print "test 1"


class Print():
    # normal method
    def test(self):
        print "test 2"

    # static method
    @staticmethod
    def test_static():
        print "test static"


def main():
    obj = Print()

    func_name = "test"
    static_name = "test_static"

    # use eval() to get the string value from a var
    eval(func_name)()

    # use getattr() to get method from a class or an instance
    # you can use is_callable() to judge if it's a method
    getattr(obj, func_name)()

    mtd = getattr(obj, func_name)
    mtd()

    getattr(Print, static_name)()


if __name__ == '__main__':
    main()

运行结果:

$ python import_func.py 
test 1
test 2
test static
test 2
展开阅读全文

没有更多推荐了,返回首页