首页 > 代码库 > 装饰器

装饰器

 

装饰器的内部实现原理

python允许将方法当作参数传递开放封闭原则

 

第一个小例子

装饰器是函数,只不过该函数可以具有特殊的含义,装饰器用来装饰函数或类,使用装饰器可以在函数执行前和执行后添加相应操作。

def wrapper(func):    def result():        print ‘before‘        func()        print ‘after‘    return result @wrapperdef foo():    print ‘foo‘

 

 传参装饰器

def outer(func):    def inner(*args,**kwargs):        print("你蛮大爷我来了")        print(kwargs)        r = func(*args,**kwargs)        print(kwargs)        print("刀妹")        return r    return inner@outerdef index(*args, **kwargs):    print("安妮")    return "lalal"index(1, **{"a":"b"})

 

使用两个装饰器

#++++++++++++++++++++++++++++++++++def outer_jia(func):    def inner1(*args, **kwargs):        print("懒辅助")        r1 = func(*args, **kwargs)        return r1    return inner1def outer(func):    def inner(*args,**kwargs):        print("我是你蛮大爷")        r = func(*args, **kwargs)        print("我是你上单刀奶奶")        return r    return inner@outer_jia@outerdef index(a1, a2):    print("烈焰天使.彦")index(1,2)

 

 

技术分享
import functoolsdef wrapper(func):    @functools.wraps(func)    def wrapper():        print before        func()        print after    return wrapper@wrapperdef foo():    print foo
View Code
技术分享
#!/usr/bin/env python#coding:utf-8 def Before(request,kargs):    print before     def After(request,kargs):    print after  def Filter(before_func,after_func):    def outer(main_func):        def wrapper(request,kargs):                         before_result = before_func(request,kargs)            if(before_result != None):                return before_result;                         main_result = main_func(request,kargs)            if(main_result != None):                return main_result;                         after_result = after_func(request,kargs)            if(after_result != None):                return after_result;                     return wrapper    return outer     @Filter(Before, After)def Index(request,kargs):    print index          if __name__ == __main__:    Index(1,2)
View Code

 

装饰器