import time
# 装饰器接受参数, 这里是函数
def get_account(func):
# 接收形参
def call_fun(text):
# 打印实参
print("参数值:", text)
time_start = time.time()
print("start:", time_start)
# 函数调用
func(text)
time_end = time.time()
print("end:", time_end)
print("耗时:", time_end-time_start, "s")
return call_fun
# 声明装饰器get_account
# 在运行函数前,会先运行这个函数前的装饰器。装饰器一般用于代码重复量较大的时候,
# 如果某些代码需要重复复用, 可以使用装饰器, 使用时只需要 @装饰器名 即可
# 此外某句代码需要重复修饰时
# 就比如系统登陆的校验,在装饰器中检验一下token值,以后呢代码就可以直接调用。
@get_account
def get_next(text):
time.sleep(2)
get_next("hellow_world")
# 打印函数名
print(get_next.__name__)
# 等价于:
# fun_closer=get_account(get_next)
# fun_closer("hellow_world")
-------------------------------------------------------------------
# 传递装饰器提示信息
def tips(arg):
def count_closer(func):
def count_num(text):
# 打印装饰器信息
print("start:", arg)
func(text)
print("end", arg)
return count_num
return count_closer
@tips("装饰器提示信息")
def count_test(text):
print(text)
count_test("count_test called")
# 等价于:
# closer_f=tips("装饰器提示信息")
# closer_s=closer_f(count_test)
# closer_s("count_test called")
Python-函数装饰器
于 2023-04-15 14:07:42 首次发布