问题描述
假设您有一个装饰器,它接受一个参数作为输入 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()
问题:如何从 `main.py' 更改 N
?
我的尝试是将 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