Python 装饰器组成

Python decorator composition

下面的示例代码演示了装饰器的工作原理。它接受一个函数 get_text(name) 并用一个函数 p_decorate(func) 包装它。

我无法理解函数 p_decorate 是如何知道参数 namefunc 的提供参数的?因为 funcp_decorate 的定义中没有参数?有人可以解释一下吗?到目前为止,我知道装饰器如何使用没有参数的函数,但这让我很头疼。

def get_text(name):  #This is fine                                                                    
    return "lorem ipsum, {0} dolor sit amet".format(name)                                

def p_decorate(func):                                                                    
    def func_wrapper(name):   #How does it know that name is part of func?                                                           
        return "<p>{0}</p>".format(func(name))                                           
    return func_wrapper                                                                  

my_get_text = p_decorate(get_text)                                           

print my_get_text("John") 

输出:

<p>lorem ipsum, John dolor sit amet</p>

编写该装饰器的开发人员对该名称进行了硬编码。 Python 只知道这一点,因为 代码的作者把那个名字放在那里 。它只是局部变量的符号名称。

换句话说,命名函数参数并没有什么神奇之处。您可以将其命名为完全不同的名称,而代码仍然可以正常工作:

def p_decorate(func):
    def func_wrapper(arg1):
        return "<p>{0}</p>".format(func(arg1))
    return func_wrapper

请注意,该变量与 get_text() 函数中的 name 局部变量没有关系!同样,这只是 that 函数中的局部变量名称。对于位置参数,重要的是调用时参数的相对位置。传入 functioncall(...) 的第一个值被分配给被调用函数内的第一个局部变量名称。

所有这些对于装饰器来说都不是什么特别的,这适用于所有函数。