[英]How can i set a default value for a function parameter with a decorator?
I'd like to define, for the bar function, the default value to the parameter param2 :我想为 bar 函数定义参数 param2 的默认值:
def foo(default_value):
def bar(param1, param2=default_value)
"""bar does some stuff"""
return bar
bar = foo(default_value)
How would this be possible with decorators ?装饰器怎么可能做到这一点?
More globally, if someone has some documentation about how can we manipulate args and kwargs when decorating a function with argument, I would be happy to take a look.更广泛地说,如果有人有一些关于在用参数装饰函数时如何操作 args 和 kwargs 的文档,我很乐意看一看。
The syntax for decorators with arguments is different.带参数的装饰器的语法是不同的。 It should return a function that will take a function and return another function.它应该返回一个函数,该函数将接受一个函数并返回另一个函数。 For example:例如:
def foo(default_value):
def wrapped(f):
def bar(param1, param2=default_value):
print "inside bar"
print "param1=%s param%s"%(param1, param2)
return bar
return wrapped
Now when you decorate a function:现在当你装饰一个函数时:
@foo(default_value="test param2")
def test_decorator():
pass
Calling it will result in:调用它会导致:
test_decorator("test param1")
inside bar
param1=test param1 param2=test param2
Alternatively with not accepting the default value:或者不接受默认值:
test_decorator("test param1", "other test param2")
inside bar
param1=test param1 param2=other test param2
I'm not sure I understand what your sample code means, but the following seems to do what what the title of your question asks:我不确定我是否理解您的示例代码的含义,但以下内容似乎符合您问题标题的要求:
PLACE_HOLDER = object()
def default_arg(default_value):
def decorator(f):
if f.func_defaults and f.func_defaults[0] is PLACE_HOLDER:
f.func_defaults = (default_value,)
return f
return decorator
@default_arg(42)
def bar(param1, param2=PLACE_HOLDER):
"""bar does some stuff"""
print('bar({}, {}) called'.format(param1, param2))
bar(1)
Output:输出:
bar(1, 42) called
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.