• python 装饰器


    装饰器:
    
    由于函数是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数:
    
    def now():
      print '2013-120-25'
    now()
    f=now
    print f
    f()
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a6.py
    2013-120-25
    <function now at 0x0253FA70>
    2013-120-25
    
    
    
    现在,假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,
    
    
    但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
    
    
    本质上,decorator 就是一个返回函数的高阶函数。所以,我们要定义一个能打印日志的decorator,可以定义如下:
    
    
    
    def wrapper(*args):
        print '------------'
        print args
        print type(args)
        print '------------'
    wrapper(1,2,3,4)
    
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a6.py
    ------------
    (1, 2, 3, 4)
    <type 'tuple'>
    ------------
    
    Process finished with exit code 0
    
    此时传入的是个元组
    
    
    
    
    def wrapper(**kw):
        print '------------'
        print kw
        print type(kw)
        print '------------'
    wrapper(size='large', quantity=6,sex='man')
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/a6.py
    ------------
    {'quantity': 6, 'sex': 'man', 'size': 'large'}
    <type 'dict'>
    ------------
    
    
    
    
    def log(func):
        def wrapper(*args, **kw):
            print 'call %s():' % func.__name__
            return func(*args, **kw)
        return wrapper
    @log
    def now():
        print '2013-12-25'
    now()
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a17.py
    call now():
    2013-12-25

  • 相关阅读:
    poj 1753 -- Flip Game
    hdu 2209 -- 翻纸牌游戏
    文件系统的挂载与卸载挂载
    我的vim配置(一)
    Poj 3687 -- Labeling Balls
    主动激发“onclick”事件;prompt
    this
    函数嵌套
    调用函数时传递的实参个数arguments.length; ,函数定义时的形参个数sum.length
    回调函数,用户定义的排序规则
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349450.html
Copyright © 2020-2023  润新知