文章目录
- 前言
- 一、闭包(Closure)
- 1.1 什么是闭包?
- 1.2 闭包的工作原理
- 1.3 闭包的实际应用
- 二、装饰器(Decorator)
- 2.1 什么是装饰器?
- 2.2 装饰器的不同形式
- 2.3 类装饰器
前言
本文主要介绍闭包的概念以及特殊的闭包装饰器的基础知识。
一、闭包(Closure)
1.1 什么是闭包?
闭包是一个引用了外部作用域中变量的函数,即使外部函数已经执行完毕,内部函数仍然可以访问和修改这些变量。
pythonprint("闭包的基本概念:")print("="*50)# 闭包示例defouter_function(msg):"""外部函数"""message=msg# 自由变量definner_function():"""内部函数 - 闭包"""returnf"内部函数访问:{message}"returninner_function# 返回内部函数(闭包)# 创建闭包closure1=outer_function("Hello")closure2=outer_function("Python")# 使用闭包print(f"closure1():{closure1()}")print(f"closure2():{closure2()}")print(f"closure1的类型:{type(closure1)}")print(f"closure1.__closure__:{closure1.__closure__}")print(f"closure1.__closure__[0].cell_contents:{closure1.__closure__[0].cell_contents}")1.2 闭包的工作原理
pythonprint("\n闭包的工作原理:")print("="*50)defcounter_factory():"""闭包工厂函数 - 创建计数器"""count=0# 自由变量defcounter():"""闭包函数"""nonlocalcount# 声明count为非局部变量count+=1returncountreturncounter# 创建多个独立的计数器counter_a=counter_factory()counter_b=counter_factory()print("计数器A:")foriinrange(3):print(f" 第{i+1}次调用:{counter_a()}")print("\n计数器B:")foriinrange(3):print(f" 第{i+1}次调用:{counter_b()}")print("\n闭包的特性验证:")print("1. 每个闭包有自己独立的状态")print("2. 闭包可以记住并修改外部变量")print(f"3. counter_a is counter_b:{counter_aiscounter_b}")1.3 闭包的实际应用
pythonprint("\n闭包的实际应用:")print("="*50)# 应用1:配置管理器defconfig_manager(initial_config):"""配置管理器 - 使用闭包实现"""config=initial_config.copy()defget(key):"""获取配置"""returnconfig.get(key)defset(key,value):"""设置配置"""config[key]=valuereturnf"已设置{key}={value}"defshow_all():"""显示所有配置"""returnconfig# 返回一个包含多个方法的字典return{'get':get,'set':set,'show':show_all}# 使用配置管理器manager=config_manager({'host':'localhost','port':8080})print("初始配置:",manager['show']())print("获取host:",manager['get']('host'))print("设置新配置:",manager['set']('debug',True))print("更新后配置:",manager['show']())# 应用2:函数工厂defpower_factory(exponent):"""创建幂函数 - 闭包作为函数工厂"""defpower(base):returnbase**exponentreturnpower# 创建不同的幂函数square=power_factory(2)# 平方函数cube=power_factory(3)# 立方函数sqrt=power_factory(0.5)# 平方根函数print(f"\n平方函数: 5² ={square(5)}")print(f"立方函数: 5³ ={cube(5)}")print(f"平方根函数: √25 ={sqrt(25)}")二、装饰器(Decorator)
2.1 什么是装饰器?
装饰器是一种特殊的闭包应用,用于修改或增强函数的功能,而不改变原函数的定义。
pythonprint("\n装饰器基础:")print("="*50)# 最简单的装饰器defsimple_decorator(func):"""简单装饰器"""defwrapper():print("函数执行前...")result=func()print("函数执行后...")returnresultreturnwrapper@simple_decoratordefsay_hello():"""业务函数"""print("Hello, World!")return"执行完成"# 使用装饰器result=say_hello()print(f"返回值:{result}")2.2 装饰器的不同形式
- 装饰带参数的函数
pythonprint("\n装饰带参数的函数:")print("="*50)deflog_decorator(func):"""记录函数调用的装饰器"""defwrapper(*args,**kwargs):print(f"调用函数:{func.__name__}")print(f"参数: args={args}, kwargs={kwargs}")result=func(*args,**kwargs)print(f"返回值:{result}")returnresultreturnwrapper@log_decoratordefadd(a,b):"""加法函数"""returna+b@log_decoratordefgreet(name,greeting="Hello"):"""问候函数"""returnf"{greeting},{name}!"# 测试print("测试add函数:")print(f"结果:{add(3,5)}")print("\n测试greet函数:")print(f"结果:{greet('Alice',greeting='Hi')}")print(f"结果:{greet('Bob')}")- 装饰器带参数
pythonprint("\n装饰器带参数:")print("="*50)defrepeat(num_times):"""重复执行装饰器"""defdecorator(func):defwrapper(*args,**kwargs):results=[]foriinrange(num_times):print(f"第{i+1}次执行:")result=func(*args,**kwargs)results.append(result)returnresultsreturnwrapperreturndecorator@repeat(3)defsay_hi(name):"""简单的问候函数"""returnf"Hi,{name}!"# 测试print("测试重复装饰器:")results=say_hi("Charlie")print(f"所有结果:{results}")- 多个装饰器
pythonprint("\n多个装饰器:")print("="*50)defbold_decorator(func):"""加粗装饰器"""defwrapper(*args,**kwargs):result=func(*args,**kwargs)returnf"**{result}**"returnwrapperdefitalic_decorator(func):"""斜体装饰器"""defwrapper(*args,**kwargs):result=func(*args,**kwargs)returnf"*{result}*"returnwrapper# 多个装饰器的应用顺序:从下往上@bold_decorator@italic_decoratordefget_text():"""获取文本"""return"装饰器测试"# 相当于:bold_decorator(italic_decorator(get_text))print("装饰后的文本:",get_text())2.3 类装饰器
pythonprint("\n类装饰器:")print("="*50)# 类作为装饰器classTimerDecorator:"""计时装饰器类"""def__init__(self,func):self.func=funcdef__call__(self,*args,**kwargs):importtime start_time=time.time()result=self.func(*args,**kwargs)end_time=time.time()print(f"函数{self.func.__name__}执行时间:{end_time-start_time:.6f}秒")returnresult@TimerDecoratordefslow_function():"""模拟耗时函数"""importtime time.sleep(0.5)return"任务完成"print("测试计时装饰器:")result=slow_function()print(f"结果:{result}")# 带参数的类装饰器print("\n带参数的类装饰器:")print("="*50)classRetryDecorator:"""重试装饰器类"""def__init__(self,max_retries=3):self.max_retries=max_retriesdef__call__(self,func):defwrapper(*args,**kwargs):forattemptinrange(self.max_retries):try:print(f"第{attempt+1}次尝试...")returnfunc(*args,**kwargs)exceptExceptionase:ifattempt==self.max_retries-1:raiseeprint(f"失败:{e}, 准备重试...")returnwrapper@RetryDecorator(max_retries=3)defrisky_operation():"""有风险的函数"""importrandomifrandom.random()<0.7:raiseValueError("随机失败")return"操作成功"print("测试重试装饰器:")try:result=risky_operation()print(f"结果:{result}")exceptExceptionase:print(f"最终失败:{e}")