python - 将 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'
它有效,但这是正确的吗?如果没有,我该怎么写?
解决方案
推荐阅读
- javascript - 仅提交填充的文本框值并丢弃空文本框 ih form php
- tensorflow - 当层的权重不是正态分布时是什么意思
- css - 在 Stylus 迭代中使用 CSS 变量
- java - 从字面上构建我自己的多维锯齿状阵列
- python - 气流 - 松弛通知。当我的程序使用气流失败时,我正在尝试配置松弛通知
- laravel-5 - 如何在 Laravel 5.6 应用程序中突出显示当前活动菜单?
- c - C hsearch 查找操作总是返回错误的数据值但正确的键值
- laravel-5 - 如何在 laravel 中修改请求文本
- java - 将列映射到 Map hibernate
- git - 如果我是所有者,如何分叉 GitHub 存储库