zoukankan      html  css  js  c++  java
  • 【Python】Flask中@wraps的使用

      

      先说总结,白话来讲,@wraps相当于是装饰器的装饰器。

      python内置的方法使用解释,看起很复杂的样子┓( ´∀` )┏

    def wraps(wrapped,
              assigned = WRAPPER_ASSIGNMENTS,
              updated = WRAPPER_UPDATES):
        """Decorator factory to apply update_wrapper() to a wrapper function
    
           Returns a decorator that invokes update_wrapper() with the decorated
           function as the wrapper argument and the arguments to wraps() as the
           remaining arguments. Default arguments are as for update_wrapper().
           This is a convenience function to simplify applying partial() to
           update_wrapper().
        """
        return partial(update_wrapper, wrapped=wrapped,
                       assigned=assigned, updated=updated)
    

      

      下面举个栗子:

    from functools import wraps
    
    # 用户角色权限确认
    def permission_required():
        def decorator(f):
            #@wraps(f)
            def decorated_function():
                return 'this is decorated function'
            return decorated_function
        return decorator
    
    # 管理员权限确认
    def admin_required(f):
        return permission_required()(f)
    
    if __name__=='__main__':
        def test_func():
            return 'this is test function'
        print(admin_required(test_func))
    

      

      不用@wraps时,打印出来是酱婶儿的

    <function permission_required.<locals>.decorator.<locals>.decorated_function at 0x00000000030411E0>
    

      

      使用之后看起来清爽了很多

    <function test_func at 0x0000000002FC11E0>
    

      

      通过对比结果,@wraps的作用猜出来个大概。

      使用之后它返回的是参数test_func方法的地址。也就是说,如果你想使用参数方法的一些属性,就需要使用@wraps了。

  • 相关阅读:
    python学习第十一天 -- 函数式编程
    python学习第十天 -- 函数
    python学习第九天 -- 列表生产式
    python学习第八天 -- 迭代
    (转载)C# 编程 使用可空类型
    Func的介绍——c#封装的代理
    select SCOPE_IDENTITY()用法
    insert into 语句的三种写法
    面试感悟----一名3年工作经验的程序员应该具备的技能
    SQL中常用模糊查询的四种匹配模式&&正则表达式
  • 原文地址:https://www.cnblogs.com/lilip/p/10755390.html
Copyright © 2011-2022 走看看