Python裝飾器是一種在不修改原始函數代碼的情況下,為函數增加新功能的方法。它們可以通過以下方式增強程序的穩定性:
import functools
import logging
logging.basicConfig(level=logging.INFO)
def log_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logging.info(f"Calling {func.__name__} with args: {args} and kwargs: {kwargs}")
result = func(*args, **kwargs)
logging.info(f"{func.__name__} returned: {result}")
return result
return wrapper
@log_decorator
def add(a, b):
return a + b
add(1, 2)
import time
def performance_test_decorator(func):
@functools.wraps(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:.4f} seconds to execute")
return result
return wrapper
@performance_test_decorator
def slow_function():
time.sleep(2)
return "Slow function executed"
slow_function()
import functools
def memoize_decorator(func):
cache = {}
@functools.wraps(func)
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@memoize_decorator
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
import functools
def exception_handler_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Error occurred in {func.__name__}: {e}")
return wrapper
@exception_handler_decorator
def divide(a, b):
return a / b
print(divide(10, 2))
print(divide(10, 0))
通過使用這些裝飾器,可以在不修改原始函數代碼的情況下,增強程序的穩定性、性能和可維護性。