python動態載入模組,並獲取模組中的類與方法(類似反射)
阿新 • • 發佈:2021-01-20
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=namedef _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']}