decorator定义与使用<一>:function decorator

#!/usr/bin/python3
"""
decorator定义与使用<一>:function decorator

Function decorators are largely just syntactic sugar that runs one function(the decorated one) through 
another(the decorator,a callable object) at the end of a def statement, and rebinds the original function 
name to the result.

Deccorator of a simple function can be either a class with __call__ or a function so long as it returns a callable 
object, at the end of which a result should better be returned no matter whether the decorated function returns anything 
because the original function may return something.

The decorator function is called immediately after the definition of the decorated function, so is the decorator
class initialized.

NOTE: Decorator of a class method can only be a function. If a decorator of a class with __call__ is applied to a class method,
the 'self' argument in the decorated method would never be passed to the __call__(*args) method of the decorator class.

Following comes a simple example.
----------------------------------
def decorator_example(func,*args):
    do something to initialize
    def tmp(*args):
        do any thing you want
        return func(*args)
    return tmp
    
@decorator_example
def():
    pass
    
----------------------------------

"""
class Tracer:
    """
    Tracer是一个类形式的function decorator,用来Trace其他函数的调用。
    @Tracer
    def function_name(...):...
    """
    def __init__(self,func):
        """
        每个被此decorator修饰的函数,在其定义(声明)之后立即执行此init函数.
        参数:func即为被修饰的函数.
        """
        print('Start tracing:',func.__name__)
        self.calls=0
        self.func=func
        
    def __call__(self,*args):
        """
        调用被修饰的函数时,其实是调用此函数.
        args为调用被修饰函数时传入的参数.
        """
        #You can do whatever you want here,before the 'return'
        self.calls+=1
        print("%s calls to %s" % (self.calls,self.func.__name__))
        return self.func(*args)    

def Tracer2(func):
    """
    Tracer2是一个函数形式的function decorator。
    """
    print('decorating %s with Tracer2' % func.__name__)
    def tmp(*args):
        print('Tracer2:'+func.__name__) #You can do whatever you want here,before the 'return'.
        return func(*args)
    return tmp

@Tracer
def foo(a,b,c):
    return a+b+c

#取消下一行注释,即可验证__init__中的注释:decorator的__init__会在每个被修饰的函数定义之后立即执行,为每个函数生成一个对应的decorator    
#print('between foo and foo2')

@Tracer
def foo2(a,b,c):
    return 'foo2 '+a+b+c
@Tracer2    
def foo3(a,b):
    print('%s,%s' % (a,b))
    return 'foo3 '+a+b

if __name__=='__main__':
    print('---decorator_demo.py---')
    ret=foo3('z','x')
    print(ret)


转载于:https://my.oschina.net/aomojan/blog/614128

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值