好用的Python装饰器!
装饰器(Decorators)是Python中一种强大而灵活的功能,用于修改或增强函数或类的行为。装饰器本质上是一个函数,它接受另一个函数或类作为参数,并返回一个新的函数或类。它们通常用于在不修改原始代码的情况下添加额外的功能或功能。
@符号,将装饰器应用于目标函数或类。下面我们将介绍10个非常简单但是却很有用的自定义装饰器。@timer:测量执行时间
import time def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.2f} seconds to execute.")
return result
return wrapper
@timer
def my_data_processing_function():
# Your data processing code here
@memoize:缓存结果
def memoize(func):
cache = {}def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@memoize
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
@validate_input 数据验证
def validate_input(func):
def wrapper(*args, **kwargs):
# Your data validation logic here
if valid_data:
return func(*args, **kwargs)
else:
raise ValueError("Invalid data. Please check your inputs.")return wrapper
@validate_input
def analyze_data(data):
# Your data analysis code here
@log_results: 日志输出
def log_results(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
with open("results.log", "a") as log_file:
log_file.write(f"{func.__name__} - Result: {result}\n")
return resultreturn wrapper
@log_results
def calculate_metrics(data):
# Your metric calculation code here
suppress_errors: 优雅的错误处理
def suppress_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Error in {func.__name__}: {e}")
return Nonereturn wrapper
@suppress_errors
def preprocess_data(data):
# Your data preprocessing code here
def validate_output(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if valid_output(result):
return result
else:
raise ValueError("Invalid output. Please check your function logic.")return wrapper
@validate_output
def clean_data(data):
# Your data cleaning code here
@retry:重试执行
import time def retry(max_attempts, delay):
def decorator(func):
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Attempt {attempts + 1} failed. Retrying in {delay} seconds.")
attempts += 1
time.sleep(delay)
raise Exception("Max retry attempts exceeded.")
return wrapper
return decorator
@retry(max_attempts=3, delay=2)
def fetch_data_from_api(api_url):
# Your API data fetching code here
@visualize_results:漂亮的可视化
import matplotlib.pyplot as plt def visualize_results(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
plt.figure()
# Your visualization code here
plt.show()
return result
return wrapper
@visualize_results
def analyze_and_visualize(data):
# Your combined analysis and visualization code here
@debug:调试变得容易
def debug(func):
def wrapper(*args, **kwargs):
print(f"Debugging {func.__name__} - args: {args}, kwargs: {kwargs}")
return func(*args, **kwargs)return wrapper
@debug
def complex_data_processing(data, threshold=0.5):
# Your complex data processing code here
@deprecated:处理废弃的函数
import warnings def deprecated(func):
def wrapper(*args, **kwargs):
warnings.warn(f"{func.__name__} is deprecated and will be removed in future versions.", DeprecationWarning)
return func(*args, **kwargs)
return wrapper
@deprecated
def old_data_processing(data):
# Your old data processing code here
总结
来源:Gabe A, M.Sc。仅用于传递和分享更多信息,并不代表本平台赞同其观点和对其真实性负责,版权归原作者所有,如有侵权请联系我们删除。
-END- 推荐阅读:
10W字《R ggplot2可视化教程1.0》来了! 详解Python列表推导式|迭代器|生成器|匿名函数 Jupyter Notebook的16个超棒插件! 临床WGS/WES/Gene Panel/Single gene异同 一图胜千言,超形象图解NumPy教程! 那些神经网络可视化利器 R Graphics Cookbook中译教程
我的学习小圈子👉 加入 赞、在看就是最大的支持