Python动态加载

动态加载模块和类

方式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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值