1 Star 0 Fork 0

silent790/python-toolbox-self-use

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
装饰器.py 1.55 KB
一键复制 编辑 原始数据 按行查看 历史
silent790 提交于 2022-04-26 17:24 . init "
""" 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()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/silent790/python-toolbox-self-use.git
git@gitee.com:silent790/python-toolbox-self-use.git
silent790
python-toolbox-self-use
python-toolbox-self-use
master

搜索帮助