Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 装饰器:参数是如何传递给包装函数的?_Python_Decorator - Fatal编程技术网

Python 装饰器:参数是如何传递给包装函数的?

Python 装饰器:参数是如何传递给包装函数的?,python,decorator,Python,Decorator,我有下面的decorator示例 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') def makeital

我有下面的decorator示例

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')
def makeitalic(f):
def包装(*args,**kwargs):
返回“+f(参数[0])+”
退货包装
def myprint(文本):
返回文本
myprint=makeitalic(myprint)
打印myprint('hii')

输出:
hii

包装函数(内部函数)是如何获得原始函数的参数的?

这四个函数已经链接到完整的解释,因此这里有可能回答您的问题的最短解释:
(*args,**kwargs)
表示传递给
包装函数的所有参数
args
是一个元组,
kwargs
是一个字典。因此,当
wrapped
函数引用
args[0]
时,它意味着“传递的第一个参数。

wrapped函数不获取原始函数的参数。它获取可以(并且通常确实)选择传递给原始函数的参数

当您执行
myprint=makeitalic(myprint)
时,名称
myprint
现在指的是包装函数。它不再指以前定义为
myprint
的函数

因此,当您调用
myprint('hii')
时,您正在调用包装函数。原始函数还没有参数,因为它从未被调用过


wrapped
内部,您可以调用
f
。这是原始函数,您可以传递它
args[0]
,即
'hii'
。因此,现在调用原始函数。它获取包装函数的第一个参数,因为这是您选择传递它的参数。

没有其他资源。只需阅读此
myprint
是内部函数,因此它们由您显式传递:
('hii')
,并用
f转发(args[0])
。很好!两者都帮了我的忙。实际上我正在包装函数对象。myprint=makeitalic(myprint)。我正在做的是调用wrapped。对吗?对于实际执行的操作,装饰器基本上是语法糖。对于装饰器语法,您将删除行
myprint=makeitalic(myprint)
,然后在
def
上方添加
@makeitalic
。您是否对wrapped如何接收参数*args或makeitalic如何接收func“myprint”感到困惑,希望我能尝试解释一下。
Output:
<I>hii</I>