装饰器(decorator)
装饰器是指在不干扰函数原本功能的基础上,额外为函数添加一个功能.
# 首先是最普通的装饰器
import time
def show_time(func):# 第一个参数永远是你的函数
#可以写多层
def wrapper(*args,**kwargs):
# 写一个统计函数运行时间的功能!
s_time = time.time()
myfunc = func(*args,**kwargs)
a_time = "%d"%(time.time() - s_time)
print("总用时 ",a_time)
return myfunc
return wrapper
@show_time
def say_hello(username):
print("hello!",username)
say_hello("chrisiven")
-------------------------------------------------------------------------------------
# 第二,带参数的装饰器
import time
def show_times(logger): #你传递的数据
def wrapper(func): #你的函数
def exec(*args,**kwargs):#你的函数参数,如果有的话
print("已经被{}控制".format(logger))
myfunc = func(*args,**kwargs)
return myfunc
return exec
return wrapper
@show_times("logger")#在定义你的主函数时进行传递!
def say_hello(username):
print("hello,{}".format(username))
say_hello("chrisiven")
--------------------------------------------------------------------------------------
## 第三,类装饰器
使用类装饰器的时候,其核心思想时把你的整个类当作装饰器!
class Decorator:
def __init__(self,func):
self.function = func
def __call__(self, *args, **kwargs):
start_time = time.time()
time.sleep(1)
myfunc = self.function(*args, **kwargs)
end_time = "%d秒" % (time.time() - start_time)
print(end_time)
return myfunc
@Decorator
def hello():
print("hello")
hello() # 调用