首页 > 解决方案 > 在装饰方法中重新启动装饰器的参数

问题描述

假设您有一个装饰器,它接受一个参数作为输入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 = 20main.pyfuncs.testMethod使用N=10.

标签: pythonmethodsdecorator

解决方案


我的解决方法是这样的。我从装饰器中删除了参数,并将其作为参数处理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

推荐阅读