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