实用函数模式
常见函数设计模式
实用函数模式有助于在 Python 中高效且优雅地解决反复出现的编程挑战。
工厂模式
def create_strategy(strategy_type):
strategies = {
'math': lambda x, y: x + y,
'string': lambda x, y: str(x) + str(y),
'list': lambda x, y: [x, y]
}
return strategies.get(strategy_type, lambda x, y: None)
add_math = create_strategy('math')
add_string = create_strategy('string')
print(add_math(5, 3)) ## 返回 8
print(add_string(5, 3)) ## 返回 '53'
记忆化模式
def memoize(func):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
@memoize
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
函数模式比较
模式 |
目的 |
关键特征 |
工厂模式 |
对象创建 |
动态方法选择 |
记忆化模式 |
缓存 |
性能优化 |
装饰器模式 |
修改 |
扩展函数行为 |
回调模式
def process_data(data, success_callback, error_callback):
try:
result = [x * 2 for x in data]
success_callback(result)
except Exception as e:
error_callback(e)
def on_success(result):
print("处理成功:", result)
def on_error(error):
print("发生错误:", error)
process_data([1, 2, 3], on_success, on_error)
管道模式
graph LR
A[输入数据] --> B[转换 1]
B --> C[转换 2]
C --> D[转换 3]
D --> E[最终输出]
def create_pipeline(*functions):
def pipeline(data):
result = data
for func in functions:
result = func(result)
return result
return pipeline
def clean_data(data):
return [x.strip() for x in data]
def remove_duplicates(data):
return list(set(data))
def sort_data(data):
return sorted(data)
data_pipeline = create_pipeline(clean_data, remove_duplicates, sort_data)
result = data_pipeline([' apple ','banana', 'apple ', 'cherry'])
print(result) ## ['apple', 'banana', 'cherry']
函数组合
from functools import reduce
def compose(*functions):
return reduce(lambda f, g: lambda x: f(g(x)), functions)
def double(x): return x * 2
def increment(x): return x + 1
composed_func = compose(double, increment)
print(composed_func(3)) ## 返回 8
错误处理模式
def safe_division(func):
def wrapper(a, b):
try:
return func(a, b)
except ZeroDivisionError:
return "不能除以零"
except TypeError:
return "无效输入类型"
return wrapper
@safe_division
def divide(a, b):
return a / b
print(divide(10, 2)) ## 返回 5.0
print(divide(10, 0)) ## 返回错误消息
上下文管理
class FileProcessor:
def __init__(self, filename, mode='r'):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
def process_file(filename):
with FileProcessor(filename) as f:
content = f.read()
## 处理文件内容
最佳实践
- 保持函数专注
- 使用适当的设计模式
- 实现健壮的错误处理
- 考虑性能影响
通过掌握这些实用函数模式,你将在你的 LabEx Python 项目中编写更高效且可维护的代码。