python 装饰器

装饰器函数:

def function_wrapper(wrapped):
    def _wrapper(*args, **kwargs):
        return wrapped(*args, **kwargs)
return _wrapper

@function_wrapper
def function():
def deco(argv):  
    def decorator(func):  
        print("decorator")  
        return func  
    print("deco")  
    print(argv)  
    return decorator  
 
@deco("123")  
def foo():  
    print("foo")  
  
foo()  

注意多个装饰器的执行顺序,应该是先执行下面的,然后是上面的。这里应先执行deco1,然后是deco2。

def deco1(func):  
    print("deco1")  
    return func  
  
def deco2(func):  
    print("deco2")  
    return func  
 
@deco2  
@deco1  
def foo():  
    print("foo")  
  
foo()  
def makebold(func):  
    def wrapped():  
        return "<b>" + func() + "</b>"  
    return wrapped  
  
def makeitalic(func):  
    def wrapped():  
        return "<i>" + func() + "</i>"  
    return wrapped  
 
@makebold  
@makeitalic  
def say():  
    return "Hello"  
  
print(say()) 

output:
<b><i>Hello</i></b> 

 

 

装饰器类:

class function_wrapper(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
    def __call__(self, *args, **kwargs):
        return self.wrapped(*args, **kwargs)
 
@function_wrapper
def function():
    pass

 

python 内置装饰器说明:https://docs.python.org/2/howto/descriptor.html#descriptor-example

 

posted @ 2015-12-11 13:31  道以万计  阅读(223)  评论(0编辑  收藏  举报