装饰器

一、函数传参

def t1():
    print "t1"

def t2(func):
    print func     # 
    func()         # 输出t1
    print "t2"     # 输出t2

t2(t1)

二、如果每个函数都需要同一个功能

def log(func):
    print "logging ..."
    func()

def foo():
    print "this is foo"

def bar():
    print "this is bar"

log(bar)   
#在实际函数外包裹一个功能函数,破坏了代码结构,很复杂

三、装饰器实现

def log(func):
    def wrapper():
        print "logging ..."
        func()
    return wrapper

@log
def foo():
    print "this is foo"

@log
def bar():
    print "this is bar"

bar()    #先进入log函数,返回wrapper时进入wrapper执行print,执行func函数
foo()

四、被装饰函数有参数情况

def log(func):
    def wrapper(*args):
        print "logging ..."
        func(*args)
    return wrapper

@log
def foo(name,age):
    print "this is %s" %name
    print "he is %d" %age


foo("abc",99)

####################################################
def log(func):
    def wrapper(*args, **kwargs):
        # args是一个参数数组,kwargs一个关键字字典
        print "logging ..."
        func(*args, **kwargs)
    return wrapper

@log
def foo(*args, **kwargs):
    for arg in args:
        print arg

    for k, v in kwargs.items():
        print k, v


foo(1,2,3,name='abc',age=99)

五、带参数的装饰器

def log(level):
    def decorator(func):
        def wrapper(**kwargs):
            if level==1:
                print "logging level = 1..."
            else:
                print "logging level != 1..."
            func(**kwargs)
        return wrapper
    return decorator

@log(level=2)
def foo(**kwargs):
    print "this is %s" % kwargs['name']
    print "he is %d" % kwargs['age']


foo(name='abc', age=99)

六、类装饰器

主要通过call函数进行调用

class Log():
    def __init__(self,func):
        self.func=func

    def __call__(self, **kwargs):
        print "logging use decorator class"
        self.func(**kwargs)
        print "decorator class end"

@Log
def foo(**kwargs):
    print "this is %s" % kwargs['name']
    print "he is %d" % kwargs['age']


foo(name='abc', age=99)

七、多个装饰器

def a(func):
    def wrapper():
        print "aaaa"
        return func()
    return wrapper

def b(func):
    def wrapper():
        print "bbbb"
        return func()
    return wrapper

def c(func):
    def wrapper():
        print "cccc"
        return func()
    return wrapper

@a
@b
@c
def foo():
    print "this is foo"


foo()  # 先a,再b,再c,再foo

其他:装饰器简单实例

#coding:utf-8

import time
"""
装饰器器:先进入装饰器器,func就是now函数
"""
def log1(func):
    def wrapper(*args, **kw):
        print "call,",func.__name__
        func()
    return wrapper
#log1:返回wrapper时,进入wrapper,执行print,然后执行func
#>>> call,now
#>>> 152.....

def log2(func):
    def wrapper(*args, **kw):
        print "call,",func.__name__
    func()
    return wrapper
#log2:先执行func,再在返回wrapper时,进入wrapper,执行print
#>>> 152.....
#>>> call,now

@log1
def now():
    print time.time()

now()
# 本质上 log1(now)

你可能感兴趣的:(装饰器)