python - 在装饰方法中重新启动装饰器的参数
问题描述
假设您有一个装饰器,它接受一个参数作为输入decor(N)
。此装饰器用于装饰模块中的方法funcs.py
# funcs.py
@decor(N=10)
def testMethod():
# do something
return something
这个funcs.py
模块现在被导入到调用的main.py
地方testMethod
。
# main.py
import funcs as funcs
funcs.testMethod()
问题:我怎样才能改变N
`main.py' ?
我的尝试是设置N
为 的属性funcs.py
,但是当我尝试在 中更改此属性时funcs.N = 20
,main.py
请funcs.testMethod
使用N=10
.
解决方案
我的解决方法是这样的。我从装饰器中删除了参数,并将其作为参数处理main.py
# funcs.py
N=10
def decor(function):
def run_function_for_some_N(*args, **kwargs):
if N == 10:
print(f'N = {N}. Run testMethod ')
return function(*args, **kwargs)
else:
print('N != 10. Will not run testMethod')
return run_function_for_some_N
@decor
def testMethod():
print('hello world')
我现在可以N
改变main.py
# main.py
import funcs as funcs
for funcs.N in [10,11]:
funcs.testMethod()
输出
N = 10. Run testMethod
hello world
N != 10. Will not run testMethod
推荐阅读
- azure - 无法连接到 Elasticsearch 服务器
- android - 来自 XML 的绑定适配器传递数组
- django - 为每位运动员选择最快的时间
- three.js - 在 Three.Js 中剪裁一个体积,给出黑色区域而不是内部材质
- php - 将完整帖子与来自两种不同帖子类型的 4 个摘录相结合
- python - 如何从 python PLY 中的方案解释“do”循环
- ruby-on-rails - 带有多个参数的 Model.where() 并检查它们是否存在于导轨中
- ios - 为 UITextView 调整FontSizeToFitWidth
- r - 遍历行并计算与 R 中的多个条件匹配的行数
- regex - 在 Mac 上使用 grep 和 TextWrangler 拆分文件的内容(搜索和替换)