代码拉取完成,页面将自动刷新
""" blue print for decorator """
from functools import wraps
import time
import numpy
# def timer(func, *args, **kwargs):
# # 包裹,保证不被覆盖
# @wraps(func)
# def timer_it(*args):
# start = time.time()
# res = func(*args)
# end = time.time()
# print(f"do function {func.__name__} used time {end-start} seconds")
# return res
# return timer_it
# @timer
# def check(num):
# ans = []
# for i in range(num):
# ans.append(i)
# return ans
# @timer
# def check_2():
# time.sleep(2)
# return "finished"
# print(check(10))
# print(check_2())
# print(check.__name__)
# 标准装饰器模板
def decorator(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
return f"Function {f.__name__} can not run"
return f(*args, **kwargs)
return decorated
@decorator
def func(n, flag = "good"):
ans = []
for i in range(n):
ans.append(i)
print(f"{flag}")
return ans
can_run = True
print(func(3), func.__name__)
# 函数实现日志装饰器模板:
from functools import wraps
def logit(file = "out.log"):
def logging_decorator(func):
@wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__+"was called"
print(log_string)
with open(file, "w") as f:
f.write(log_string)
return func(*args, **kwargs)
return wrapped_function
return logging_decorator
#test
# @logit()
# def myfunc1():
# pass
# myfunc1()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。