一沥邻、函數(shù)傳參
def t1():
print "t1"
def t2(func):
print func # <function t1 at 0x10aae2668>
func() # 輸出t1
print "t2" # 輸出t2
t2(t1)
二、如果每個(gè)函數(shù)都需要同一個(gè)功能
def log(func):
print "logging ..."
func()
def foo():
print "this is foo"
def bar():
print "this is bar"
log(bar)
#在實(shí)際函數(shù)外包裹一個(gè)功能函數(shù)羊娃,破壞了代碼結(jié)構(gòu)唐全,很復(fù)雜
三、裝飾器實(shí)現(xiàn)
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() #先進(jìn)入log函數(shù)蕊玷,返回wrapper時(shí)進(jìn)入wrapper執(zhí)行print芦瘾,執(zhí)行func函數(shù)
foo()
四、被裝飾函數(shù)有參數(shù)情況
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是一個(gè)參數(shù)數(shù)組集畅,kwargs一個(gè)關(guān)鍵字字典
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)
五近弟、帶參數(shù)的裝飾器
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)
六、類(lèi)裝飾器
主要通過(guò)call函數(shù)進(jìn)行調(diào)用
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)
七挺智、多個(gè)裝飾器
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
其他:裝飾器簡(jiǎn)單實(shí)例
#coding:utf-8
import time
"""
裝飾器器:先進(jìn)入裝飾器器二鳄,func就是now函數(shù)
"""
def log1(func):
def wrapper(*args, **kw):
print "call,",func.__name__
func()
return wrapper
#log1:返回wrapper時(shí),進(jìn)入wrapper媒怯,執(zhí)行print订讼,然后執(zhí)行func
#>>> call,now
#>>> 152.....
def log2(func):
def wrapper(*args, **kw):
print "call,",func.__name__
func()
return wrapper
#log2:先執(zhí)行func,再在返回wrapper時(shí)扇苞,進(jìn)入wrapper欺殿,執(zhí)行print
#>>> 152.....
#>>> call,now
@log1
def now():
print time.time()
now()
# 本質(zhì)上 log1(now)