装饰器是一个函数,主要用途是用来包装另一个函数或者类。首要目的是是为了透明修改或增强包装对象的行为。表示装饰器的语法是特殊符号@,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。
def deco(func): def inner(): print('do something') func() return inner @deco def play(): print('please') play()
当有两个或者以上的装饰器的时候,先用第二个装饰器进行装饰,接着再用第一个装饰器进行装饰,而在调用过程中,先执行第一个装饰器,接着再执行第二个装饰器
def deco1(func): print('deco1 show time') def inner(): print('I find a girl') return 'yeah! '+func() return inner def deco2(func): print('deco2 show time') def inner(): print('But I have no idea') return 'come on,'+func() return inner @deco1 @deco2 def boy(): d = 'you should do something' return d print(boy()) 运行结果: deco2 show time deco1 show time I find a girl But I have no idea yeah! come on,you should do something
对于有参数的函数进行装饰
def deco(func):#如果原函数有参数,那闭包函数必须保持参数个数一致,并且将参数传递给原方法 def inner(name): #被装饰的函数有形参,闭包函数必须有参数 print('something just like this') a=func(name) return a+' '+'superhero' return inner @deco def boy(name): return '{} say "doodoodoodoodoodoo"'.format(name) print(boy('song')) 运行结果 something just like this song say "doodoodoodoodoodoo" superhero
def deco(func):#函数有不定量形参 def inner(*args,**kwargs): print('something just like this') a = func(*args,**kwargs) return a+' '+'superhero' return inner @deco def boy(name1,name2): return '{} and {} say "DooDooDoo"'.format(name1,name2) @deco def func2(a,b,c): return '{}+{}+{}={}'.format(a,b,c,a+b+c) print(boy('song','wang')) print(func2(1,2,3)) 运行结果: something just like this song and wang say "DooDooDoo" superhero something just like this 1+2+3=6 superhero
带参数的装饰器,简单讲,带参数的装饰器就是在原闭包的基础上又加了一层闭包。
def deco_1(pro='song'): def deco(func): def inner(*args,**kwargs): print('the boss is {}'.format(pro)) return 'one more time,'+func(*args,**kwargs) return inner return deco @deco_1('song') def boy(name1,name2): return '{} and {},you must remember'.format(name1,name2) print(boy('wang','li')) 运行结果: the boss is song one more time,wang and li,you must remember