【问题标题】:Re-initiate decorator's argument in a decorated method在装饰方法中重新启动装饰器的参数
【发布时间】:2021-09-28 16:49:00
【问题描述】:

假设你有一个装饰器,它接受一个参数作为输入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 的属性,但是当我尝试在main.py 中更改此属性funcs.N = 20 时,funcs.testMethod 使用N=10 运行。

【问题讨论】:

标签: python methods decorator


【解决方案1】:

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

我现在可以将 Nmain.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

【讨论】:

    猜你喜欢
    • 2012-02-09
    • 2020-01-11
    • 2013-03-10
    • 2014-01-14
    • 2011-08-02
    • 1970-01-01
    • 2020-01-02
    • 2011-06-25
    • 1970-01-01
    相关资源
    最近更新 更多