您的位置:首页 > 其它

装饰器

2016-03-09 15:24 375 查看
#定义函数:
def hello(*args,**kw):
print 'ab'
print args
print kw
args=range(1,5)

hello(args) #返回值:
ab
([1, 2, 3, 4],)
{}

#定义装饰函数:
def dec(fun):
def wrapper(*args,**kw):
print 'do sth. before'
fun(*args,**kw)
print 'do sth. after'
return wrapper

dec(hello(args)) #将hello函数及参数当做变量赋予dec,只相当于直接执行hello(args),返回值:
ab
([1, 2, 3, 4],)
{}

p=dec(hello)
p(args)

dec(hello)(args) #将函数当做变量赋予dec,然后通过变量调用函数,再赋予变量变量,返回值:
do sth. before
ab
([1, 2, 3, 4],)
{}
do sth. after


def dec(fun):
def wrapper(*args,**kw):
print 'do sth. before'
fun(*args,**kw)          #此处如果改为 return fun(*args,**kw),则下一句print 'after'不会再执行。在函数中,遇到第一个return则不会再执行后面的语句,如果返回两个值,可以写在同一行。如果用了return,函数执行完会得到结果,没有return则无返回值
print 'do sth. after'
return wrapper

@dec #通过@调用装饰函数
def hello(*args,**kw):
print 'ab'
print args
print kw
args=range(1,5)

hello(args)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: