zoukankan      html  css  js  c++  java
  • python3.x 浅谈修饰器

    #装饰器用法,好处
    #简化代码,避免重复性代码
    #打印日志 @log
    #检测性能 @performance
    #数据库事务 @transaction
    #URL路由 @post('/register')

    简单例子:

    @new_addlog
    def function(x):
      return x*2
    等价于===>>
    def function(x):
      return x*2
    function=new_addlog(function)

    #修饰器用法1
    '''
    def reducedata(x):
      return x*2

    def addlog(f):
      def newFunction(data):
        print('call: '+f.__name__+'()...',data)
        return (f(data))
      return newFunction

    reducedata = addlog(reducedata)
    print(reducedata(5))
    '''

    #修饰器用法2  tips:先定义修饰器,在使用@绑定
    def addLOG(f):#指针地址不能带参
       def log(x,y):
        print('call: '+f.__name__)
        return f(x,y)
      return log

    @addLOG    #需要先定义
    def add(x,y):
      return x+y

    print(add(5,6))

    #按照道理应该cpp也能这么做,但逻辑太复杂,py风格比较好理解,

    #将需要扩展的api封装起来,增加需要的功能,完成之后,在执行封装的api,就这么简单

     扩展functools.wraps(),先看下原型api

    >>> from functools import wraps
    >>> def my_decorator(f):
    ...     @wraps(f)
    ...     def wrapper(*args, **kwds):
    ...         print('Calling decorated function')
    ...         return f(*args, **kwds)
    ...     return wrapper
    ...
    >>> @my_decorator
    ... def example():
    ...     """Docstring"""
    ...     print('Called example function')
    ...
    >>> example()
    Calling decorated function
    Called example function
    >>> example.__name__
    'example'
    >>> example.__doc__
    'Docstring'

    wraps把原函数所有必要的属性复制到新函数上,与原来简单的装饰器相比不只是增加了新功能,还

    保留原函数的属性。

  • 相关阅读:
    ggplot2|theme主题设置,详解绘图优化-“精雕细琢”-
    ggplot2|theme主题设置,详解绘图优化-“精雕细琢”
    阻抗设计01
    Geber文件,装配图,BOM表的输出
    c语言里面你不知道的break与switch,contiune的用法
    数据结构之链表学习01
    数据结构概念及连续存储数组的算法演示
    使用malloc和free函数进行内存动态分配
    浅谈结构体
    浅谈指针01
  • 原文地址:https://www.cnblogs.com/liuruoqian/p/11309250.html
Copyright © 2011-2022 走看看