装饰器

 

装饰器的内部实现原理

python允许将方法当作参数传递

开放封闭原则

 

第一个小例子

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

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

 

 传参装饰器

def outer(func):
    def inner(*args,**kwargs):
        print("你蛮大爷我来了")
        print(kwargs)
        r = func(*args,**kwargs)
        print(kwargs)
        print("刀妹")
        return r
    return inner
@outer
def 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 inner1
def outer(func):
    def inner(*args,**kwargs):
        print("我是你蛮大爷")
        r = func(*args, **kwargs)
        print("我是你上单刀奶奶")
        return r
    return inner
@outer_jia
@outer
def index(a1, a2):
    print("烈焰天使.彦")
index(1,2)

 

 

import functools


def wrapper(func):
    @functools.wraps(func)
    def wrapper():
        print 'before'
        func()
        print 'after'
    return wrapper

@wrapper
def 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

 类装饰器, 用装饰圈修饰类

def decorator(args):
    def _deco(func):
        def _func(self):
            # 注意 self 是作为参数传进来的
            self.i = args
            func(self)
            
        return _func

    return _deco

class Foo(object):
    @decorator(123)
    def bar(self):
        # 输出 123
        print('i:', self.i)


Foo().bar()

后续加入理解,暂未理解透彻

posted @ 2016-12-18 12:33  我当道士那儿些年  阅读(353)  评论(0编辑  收藏  举报