1.装饰器
装饰:改变原有函数功能
函数作为参数,且函数作为返回值
@是装饰符号,后面跟装饰器
注意:
@decorator
在py文件被倒入时,装饰器就会运行
#解决三个问题:
1.被倒入时,装饰器运行
2.目标函数无法带参数
3.目标函数被调用后无法插入代码
#解决:利用闭包构建装饰器
def time_cost(f):
def _f(*args,**kwargs):
start=time.clock()
a=f(*args,**kwargs)
end=time.clock()
print f.__name__,'costs',end=start
return a
return _f
@time_cost
def f1(times):
return [i for i in times]
f1(100)
#解决装饰器带参数的问题:利用三层嵌套函数
def time_cost(times):
def decorator(f):
def _f(*args,**kwargs):
start=time.clock()
for i in times:
a=f(*args,**kwargs)
end=time.clock()
return a
return _f
return decorator
@time_cost
def f()
pass
三层嵌套结构解释
在两层嵌套中,@time_cost后面没有跟任何东西,其实就是,在调用目标函数时,调用的是time_cost(f)的返回值
在三层嵌套中,@time_cost(times)返回的是一个函数,然后这个函数再作为装饰 发生作用
@time_cost(times)==>@decorator==>_f(*args,**kwargs)
装饰模式例子
#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke
def printInfo(info):
print unicode(info, 'utf-8')
def wearTrouser(f):
def _f(*arg, **kwarg):
printInfo("裤子")
return f(*arg, **kwarg)
return _f
def wearSuit(f):
def _f(*arg, **kwarg):
printInfo("西服")
return f(*arg, **kwarg)
return _f
def wearTShirt(f):
def _f(*arg, **kwarg):
printInfo("T恤")
return f(*arg, **kwarg)
return _f
def wearCap(f):
def _f(*arg, **kwarg):
printInfo("帽子")
return f(*arg, **kwarg)
return _f
def wearSportShoes(f):
def _f(*arg, **kwarg):
printInfo("运动鞋")
return f(*arg, **kwarg)
return _f
def wearLeatherShoes(f):
def _f(*arg, **kwarg):
printInfo("皮鞋")
return f(*arg, **kwarg)
return _f
def wearedPerson(person,cloths):
w = person
for f in cloths:
w=f(w)
return w
#@wearTrouser
#@wearTShirt
def person(name):
printInfo("装扮好的%s" % name)
if __name__ == '__main__':
#采用装饰器时(去掉装饰器的注释),是对人依次进行穿衣服的装饰
person("晓明")
print "-----------------------"
#直接采用嵌套函数时,是每穿一件衣服,嵌套一层
#(穿西装函数(穿皮鞋函数(穿裤子函数(Person))))
business_wear=[wearLeatherShoes,wearSuit,wearTrouser]
sports_wear = [wearSportShoes,wearCap,wearTShirt,wearTrouser]
weared_business_person = wearedPerson(person,business_wear)
weared_sports_person = wearedPerson(person,sports_wear)
weared_business_person("晓明")
print "-----------------------"
weared_sports_person("晓红")