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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM