• 装饰器 decorator


    装饰器

    def document_it(func):
        def new_function(*args, **kwargs):
            print('Running function:', func.__name__)
            print('Positional arguments:', args)
            print('Keyword arguments:', kwargs)
            result = func(*args, **kwargs)
            print('Result:', result)
            return result
        return new_function
    
    #def add_ints(a, b):
    #    return a + b
    #cooler_add_ints = document_it(add_ints)
    #cooler_add_ints(3, 5)
    #('Running function:', 'add_ints')
    #('Positional arguments:', (3, 5))
    #('Keyword arguments:', {})
    #('Result:', 8)
    
    #@document_it
    #def add_ints(a, b):
    #    return a + b
    
    #add_ints(3, 5)
    
    
    def square_it(func):
        def new_function(*args, **kwargs):
            result = func(*args, **kwargs)
            return result * result
        return new_function
    
    #@square_it
    #@document_it
    #def add_ints(a, b):
    #    return a + b
    
    #add_ints(3, 5)
    
    #('Running function:', 'add_ints')
    #('Positional arguments:', (3, 5))
    #('Keyword arguments:', {})
    #('Result:', 8)
    
    
    @document_it
    @square_it
    def add_ints(a, b):
        return a + b
    
    add_ints(3, 5)
    
    #('Running function:', 'new_function')
    #('Positional arguments:', (3, 5))
    #('Keyword arguments:', {})
    #('Result:', 64)
    
    #靠近函数定义的装饰器最先执行
    def log(func):
        def wrapper(*args, **kw):
            print('call %s():' % func.__name__)
            return func(*args, **kw)
        return wrapper
    
    
    @log
    def now():
        print('2015-3-25')
    
    
    now()
    
    #call now():
    #2015-3-25

    如果decorator本身需要传入参数

    def log(text):
        def decorator(func):
            def wrapper(*args, **kw):
                print('%s %s():' % (text, func.__name__))
                return func(*args, **kw)
            return wrapper
        return decorator
    
    @log('execute')
    def now():
        print('2015-3-25')
    
    now()
    
    print(now.__name__)
    
    #execute now():
    #2015-3-25
    #wrapper

    不需要编写wrapper.__name__ = func.__name__这样的代码,Python内置的functools.wraps就是干这个事的

    相当于:

    now = log(now)
    now = log('execute')(now)

  • 相关阅读:
    TokenType ([{}{}()])[{}]{}
    C# netcore 开发WebService(SoapCore)
    C++求快速幂
    二分法与牛顿迭代法求方程根
    Obtaining a Thorough CS Background Online (线上CS深度学习攻略)
    Elasticsearch 堆空间配置
    S家lic
    如何用calibredrv 来merge多个cell的gds
    siliconsmart feature
    openwrt的IPTV配置
  • 原文地址:https://www.cnblogs.com/jzm17173/p/5190431.html
Copyright © 2020-2023  润新知