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']}