python中的反射机制,解决模块动态引入,路由分发

什么是反射机制

反射是将字符串映射到实例变量或实例方法的一种机制.
常见的应用场景:(1)动态加载模块(2)web框架的URL路由

学习中的可能遇到了这些需求

(1)你的伙伴封装好了很多py文件,然后你负责根据不同需求去调用不同模块。
(2)你写了一个类,其中封装了很多方法,这时你需要提供一个统一的入口供其他人调用(类似路由转发)。
这两个问题都可以通过反射很好的解决

python中的反射

(1)__import__() 动态加载模块
(2)hasattr() 判断实例是否存在字符串对应的属性
(3)getattr() 获取字符串对应的属性
(4)setattr() 将字符串对应的已存在的属性添加到实例中
(5)delattr() 删除实例中字符串对应的属性

解决模块动态引入问题

def new_method(self):
    print("我是新来的请多关照!")


def main():
    """
    动态导入模块,并创建类实例执行其中方法
    """
    # 1 动态导入func_001模块
    func001_module = __import__("src.func_001", fromlist=True)
    print(func001_module)

    # 1.1 判断是否存在对应类
    if hasattr(func001_module, "Func001"):

        # 2 创建Func001类实例对象
        func001 = getattr(func001_module, "Func001")
        # 2.1 判断是否存在该方法
        if hasattr(func001, "process"):
            # 2.1.1 获取process成员方法
            func001_process = getattr(func001, "process")
            # 2.1.2 执行该方法
            func001_process(func001)
        else:
            print("没有找到对应的方法...")

        # 3 添加像Func001中添加new_method方法
        setattr(func001, "new_method", new_method)
        # 3.1 判断是否存在该方法
        if hasattr(func001, "new_method"):
            # 3.1.1 获取new_method成员方法
            func001_new_method = getattr(func001, "new_method")
            # 3.1.2 执行该方法
            func001_new_method(func001)
        else:
            print("没有成功添加new_method")

        # 4 删除Func001新增方法
        delattr(func001, "new_method")
        print("是否存在新增方法:", hasattr(func001, "new_method"))
    else:
        print("没有找到对应的类...")


if __name__ == "__main__":
    main()

路由转发问题

class User(object):

    def add(self):
        print("新增一名用户...")

    def delete(self):
        print("删除一名用户...")

    def update(self):
        print("更新一名用户...")

    def select(self):
        print("查询一名用户...")

    def before_process(self, method):
        if method == "add":
            self.add()
        elif method == "delete":
            self.delete()
        elif method == "update":
            self.update()
        elif method == "select":
            self.select()
        else:
            print("无效调用")

    def after_process(self, method):
        """
        类似路由转发
        :param method: str 待调用方法名
        """
        if hasattr(self, method):
            func = getattr(self, method)
            func()
        else:
            print("无效调用")


if __name__ == '__main__':
    user = User()
    # user.before_process(method="add")
    user.after_process(method="delete")

你可能感兴趣的:(python)