在Python中修改装饰器中函数的默认参数

时间:2014-08-01 09:45:59

标签: python python-2.7 wrapper decorator

我有一个装饰器来改变传递给函数的字符串参数:

def decorator(fn):
    def wrapper(*args):
        replacements = list()
        for arg in args:
            new_item = arg + "!!!"
            replacements.append(new_item)
        args = tuple(replacements)
        print fn(*args)
    return wrapper

我有一个非常简单的函数,我想将一个默认参数传递给decorator

def f1(arg1="Hello world"):
     return arg1

令我惊讶

decorator(f1)() # using the default argument

返回了未经修饰的Hello world

我做了一些研究,发现default arguments are only evaluated at function creation time。我还了解到具有默认值的参数存储在.func_defaults属性中。通过这些信息,我改变了我的装饰器,通过改变线

让它按照我想要的方式工作
for arg in args:

for arg in args + fn.func_defaults:

问题

为什么函数f1的默认参数值没有传递给包装器中的*args并按预期更改?

0 个答案:

没有答案