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)

猜你喜欢

转载自blog.csdn.net/qq_19446965/article/details/124015463