1、装饰器
定义:是一个闭包,把一个函数当作参数返回一个替代版的函数,本质上就是一个返回函数的函数
简言之,python装饰器就是用于拓展原来函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数,使用python装饰器的好处就是在不用更改原函数的代码前提下给函数增加新的功能。
#简单的装饰器
def func1():
print("sunck is a good man")
def outer(func):
def inner():
print("**********")
func()
return inner()
f=outer(func1)
复杂一点的装饰器:
def outer(func):
def inner(age):
if age < 0:
age = 0
func(age)
return inner
#say = outer(say)
#使用@符号将装饰器应用到函数
#python2.4后支持使用
@outer #相当于say=outer(say)
def say(age):
print("sunck is %d years old " %(age))
say(18)
say(-10)
通用装饰器:
def outer(func):
def inner(*args, **kwargs):
#添加修改的功能
print("&&&&&&&&&&&")
func(*args, **kwargs)
return inner
@outer
def say(name, age):#函数的参数理论上是无限制的,但实际上最好不要超过6、7个
print("my name is %s,I am %d years old " %(name,age))
say("sunck",18)
#多个装饰器
import time
def deco01(func):
def wrapper(*args, **kwargs):
print("this is deco01")
startTime = time.time()
func(*args, **kwargs)
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
print("deco01 end here")
return wrapper
def deco02(func):
def wrapper(*args, **kwargs):
print("this is deco02")
func(*args, **kwargs)
print("deco02 end here")
return wrapper
@deco01
@deco02
def func(a,b):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
if __name__ == '__main__':
f = func
f(3,4)
#func()
'''
this is deco01
this is deco02
hello,here is a func for add :
result is 7
deco02 end here
time is 1003 ms
deco01 end here
'''