如何在被装饰函数中修改装饰器内初始化的字典?
问题解决:装饰器内字典被被装饰函数修改的实现
你的代码报错是因为global_dict是inner_function的局部变量,不属于全局作用域,test_function里用global声明根本找不到这个变量,自然抛出name 'global_dict' is not defined错误。
以下是几种可行的实现方式:
方案1:将字典作为参数传递给被装饰函数
直接修改装饰器,在调用被装饰函数时把字典作为参数传入,被装饰函数接收后即可修改:
def decorator(): def inner_function(func): global_dict = {} print("Inner function") # 把字典传给被装饰函数 ret = func(global_dict) return ret return inner_function @decorator() def test_function(global_dict): global_dict["something"] = "something" print("Test function") print(global_dict) # 输出: {'something': 'something'} return True test_function()
方案2:利用闭包让函数访问字典
通过闭包特性,让被装饰的函数能直接访问装饰器内的字典,同时用functools.wraps保留原函数的元信息:
import functools def decorator(): global_dict = {} def inner_function(func): @functools.wraps(func) def wrapper(): print("Inner function") # 被装饰函数通过闭包访问global_dict func(global_dict) return True return wrapper return inner_function @decorator() def test_function(global_dict): global_dict["something"] = "something" print("Test function") print(global_dict) # 输出: {'something': 'something'} test_function()
方案3:将字典绑定为函数属性
把字典绑定到被装饰函数的属性上,这样函数内部可以通过自身属性访问并修改字典,无需额外参数:
def decorator(): def inner_function(func): global_dict = {} # 将字典绑定为函数的属性 func.global_dict = global_dict print("Inner function") ret = func() return ret return inner_function @decorator() def test_function(): # 通过函数自身属性访问字典 test_function.global_dict["something"] = "something" print("Test function") print(test_function.global_dict) # 输出: {'something': 'something'} return True test_function()
内容的提问来源于stack exchange,提问作者Tarique
相关产品推荐
相关产品推荐

