标签:装饰器
装饰器用于拓展原有函数功能的一种函数def helloWorld(fun)
def out()
print ("======start========")
fun()
print ("=====end======")
return out
@helloWorld
def back ()
print ("let‘s go")
back()
运行结果:
======start========
let‘s go
=====end======
def helloWorld(arg):
def out(fun):
def go():
print ("======start========")
fun()
print ("=====end======")
return go
return out
@helloWorld("will‘)
def back ():
print ("let‘s go")
back()
运行结果:
======start========
let‘s go
=====end======
看到装饰器自带一个参数传入,那么运行过程中这个参数会代入运行,整体的运行过程
当函数也带参数参与:
def logging(taskname):
def wrapper(func):
def retu(*args, **wkargs):
# 函数通过装饰起参数给装饰器传送参数
print (‘before task‘,taskname)
# 装饰器传变量给函数
taskid = 1
summer, funcres = func(taskid, *args, **wkargs)
print (‘after task‘, taskid, summer)
return retu
return wrapper
@logging("test")
def testd(taskid):
print ("testd runing",taskid)
return "task summer success eg",[]
testd()
运行结果和步骤:
标签:装饰器
原文地址:http://blog.51cto.com/13654063/2104926