python-通过函数名有选择的执行函数

功能描述:

校验参数时候,会根据不同的参数类型选择不同的策略进行判断,再不定义map的形况下,如何根据类型自动选择相应的函数进行校验,并且可扩展。。。

直接上代码:


class Check(object):

    def __init__(self):
        self.meta = {'type': 'int'}  # 初始化meta ----pass

    @staticmethod
    def _format_int(key: str, value):
        print("Check int type...")
        if not isinstance(value, int):
            raise TypeError(key, value)

    @staticmethod
    def _format_float(key: str, value):
        print("Check float type...")
        if not isinstance(value, float):
            raise TypeError(key, value)

    @staticmethod
    def _format_bool(key: str, value):
        print("Check bool type...")
        if not isinstance(value, float):
            raise TypeError(key, value)

    def _get_judge_func(self, type_name):
        func_name = f"_format_{str(type_name)}"
        if not hasattr(self, func_name):
            return None
        return getattr(self, func_name)

    def do_check(self, key, value):
        judge_func = self._get_judge_func(str(self.meta.get("type")))
        if judge_func:
            judge_func(key, value)


if __name__ == '__main__':
    check = Check()
    check.do_check('age', 30)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值