zoukankan      html  css  js  c++  java
  • python 函数装饰器

    # 使用一个函数来装饰另一个函数,不使用@
    
    def a_new_decorator(a_func):
    
        def wrapTheFunc():
            print("Do sth. before a_func()")
    
            a_func()
    
            print("Do sth. after a_func()")
    
        return wrapTheFunc
    
    
    def a_func_requiring_decoration():
        print("I need some decoration")
    
    a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration)
    
    a_func_requiring_decoration()
    # 输出如下:
    # Do sth. before a_func()
    # I need some decoration
    # Do sth. after a_func()
    # 使用@来运行上面的代码
    
    def a_new_decorator(a_func):
    
        def wrapTheFunc():
            print("Do sth. before a_func()")
    
            a_func()
    
            print("Do sth. after a_func()")
    
        return wrapTheFunc
    
    @a_new_decorator
    def a_func_requiring_decoration():
        print("I need some decoration")
    
    # a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration)
    
    a_func_requiring_decoration()
    the @a_new_decorator is a just a short way of saying:
    a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration)
    # 希望print(xx.__name__)的结果是xx,而不是wrapTheFunc
    # 使用functools.wraps来解决此问题
    
    from functools import wraps
    
    
    def a_new_decorator(a_func):
        @wraps(a_func)
        def wrapTheFunc():
            print("Do sth. before a_func()")
    
            a_func()
    
            print("Do sth. after a_func()")
    
        return wrapTheFunc
    
    @a_new_decorator
    def a_func_requiring_decoration():
        print("I need some decoration")
    
    # a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration)
    
    a_func_requiring_decoration()
    
    print(a_func_requiring_decoration.__name__)

    注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

  • 相关阅读:
    XML解析
    用进度条显示从网络上下载文件进度
    android—获取网络数据
    android中sharedPreferences的用法
    实现listview中checkbox的多选与记录
    利用Bundle在activity之间传递对象
    Activity使用Serializable传递对象实例
    工作框架各种使用整理 -- 页面参数传递
    ubuntu中安装VMWare tools
    工作框架各种使用整理 -- 自己处理分页且输入条件中有过滤条件
  • 原文地址:https://www.cnblogs.com/karl-python/p/14626891.html
Copyright © 2011-2022 走看看