zoukankan      html  css  js  c++  java
  • python动态加载模块,并获取模块中的类与方法(类似反射)

    temp.py:

    def func():
        print('func is called.')
    
    class A:
        def __init__(self,name='A'):
            self.name=name
    
        def _say(self,msg):
            print(msg)
    
        def sayhello(self):
            print('hello,i am {}'.format(self.name))
    
    
    class B:
        def __init__(self,name='B'):
            self.name=name
    
        def _do_work(self):
            print('Do some work.')
    
        def greet(self):
            print('hello,i am {}'.format(self.name))

    test.py:

    import inspect
    
    def get_attrs_of_module(module_name='temp'):
        module=__import__(module_name)#动态引入模块(temp.py文件)
        #用inspect.getmembers获取模块中的类
        classes=[clsname for (clsname,fullname) in inspect.getmembers(module,inspect.isclass)]
    
        dic_cls_methods={}
        for clsname in classes:
            #用python内置的getattr()方法获取模块的类,inspect.isfunction()方法过滤出该类的方法
            methods=[method_name for (method_name,method) in inspect.getmembers(getattr(module,clsname),inspect.isfunction)]
            dic_cls_methods[clsname]=methods
        print(dic_cls_methods)

    输出:

    {'A': ['__init__', '_say', 'sayhello'], 'B': ['__init__', '_do_work', 'greet']}
  • 相关阅读:
    c# 框架学习(nop )总结-------删除功能
    c# 框架学习(nop )总结-------编辑功能
    约束
    索引
    受限操作的变通解决方案
    删除数据表
    修改已有数据表
    定义外键
    定义主键
    定义默认值
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/14301750.html
Copyright © 2011-2022 走看看