美文网首页
python 装饰器以及获取全部参数

python 装饰器以及获取全部参数

作者: 孙宏志 | 来源:发表于2019-10-29 17:31 被阅读0次
    
    def log(fun):
        def inner(*args, **kwargs):
            name = "function name is {0}".format(fun.__name__)
            #获取全部参数以及参数值
            param = ''
            if len(args) > 0:
                param += ','.join(args)
            if len(kwargs) > 0:
                param += str(kwargs)
            param = "function param is {0}".format(param)
            print(name)
            print(param)
            a = fun(*args, **kwargs)
            print("response is : ", a)
            print("---" * 34)
            return a
        return inner
    
    
    @log
    def get_name(name):
        print("name is {0}".format(name))
        return "name end"
    
    
    @log
    def get_user(name, password):
        print("name is {0}, password is {1}".format(name, password))
        return "user end"
    
    
    @log
    def just_print():
        print("just print !@#@!#!#!#!#!#!")
        return
    
    
    a = get_name("123")
    b = get_user("user", "123456a")
    
    c = get_user(password="123456a", name="leo")
    d = just_print()
    
    print("a ", a)
    print("b ", b)
    print("c ", c)
    print("d ", d)
    

    结果如下:

    function name is get_name
    function param is 123
    name is 123
    response is :  name end
    ------------------------------------------------------------------------------------------------------
    function name is get_user
    function param is user,123456a
    name is user, password is 123456a
    response is :  user end
    ------------------------------------------------------------------------------------------------------
    function name is get_user
    function param is {'password': '123456a', 'name': 'leo'}
    name is leo, password is 123456a
    response is :  user end
    ------------------------------------------------------------------------------------------------------
    function name is just_print
    function param is 
    just print !@#@!#!#!#!#!#!
    response is :  None
    ------------------------------------------------------------------------------------------------------
    a  name end
    b  user end
    c  user end
    d  None
    

    相关文章

      网友评论

          本文标题:python 装饰器以及获取全部参数

          本文链接:https://www.haomeiwen.com/subject/eloructx.html