首页 > 解决方案 > 将 Python 装饰器与来自全局变量的数据一起使用

问题描述

所以我写了一些有效的代码,但我对这种风格不满意,所以你可以帮助我。包装函数循环一个全局变量并将其中的一些数据用作参数,所以当我调用一个函数时,它的参数集与定义时不同。这是代码示例:

from functools import wraps

global elems
elems = [('a','b')]

def onEachInList(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        results = [func(a, b, *args, **kwargs) for a, b in elems]
        return 'done'
   return wrapper

@onEachInList
def func_1(a, b, c):
    print(f'{a}{b}{c}')

@onEachInList
def func_2(a, b):
    print(f'{a}{b}')

现在,当我使用这些功能时,我只需调用

>>> func_1(c)
abc
'done'
>>> func_2()
ab
'done'

它有效,但这是正确的吗?如果没有,我该怎么写?

标签: pythonpython-decorators

解决方案


推荐阅读