[英]How to retrieve the name of the arguments passed in a function using Decorators
[英]Decorators: how arguments are passed to wrapped function?
我有以下装饰器示例
def makeitalic(f):
def wrapped(*args, **kwargs):
return "<I>" + f(args[0]) + "</I>"
return wrapped
def myprint(text):
return text
myprint = makeitalic(myprint)
print myprint('hii')
Output:
<I>hii</I>
包装函数(内部函数)如何获取原始函数的参数?
包装的函数不获取原始函数的参数。 它获取可以(通常)选择传递给原始函数的参数。
当您执行myprint = makeitalic(myprint)
,名称myprint
现在指的是包装函数。 它不再引用先前定义为myprint
的函数。
因此,当您调用myprint('hii')
,您正在调用包装的函数。 原始函数尚无参数,因为它从未被调用过。
内wrapped
,您将呼叫f
。 这是原始函数,您将其传递给args[0]
,即'hii'
。 因此,现在调用了原始函数。 它获取包装函数的第一个参数,因为这就是您选择传递它的方式。
thefourtheye已经与完整的解释相关联,因此,这是可能回答您问题的最简短的解释: (*args, **kwargs)
表示传递给wrapped
函数的所有参数。 args
是元组,而kwargs
是字典。 因此,当wrapped
函数引用args[0]
,它意味着“传递的第一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.