我正在尝试使用装饰器并发现它们有点酷,但我不完全理解里面发生了什么。让我们假设一个简单的例子,我从其中一个关于装饰器的页面借来的。
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
get_text = p_decorate(get_text)
print(get_text("John"))
让我对p_decorate
函数感到困惑的是我们从哪里得到name
参数?我将描述我对程序的理解。
get_text
参数name
函数
p_decorate
参数创建装饰器函数func
,这显然是我们的get_text
函数p_decorate(get_text)
时,func
的{{1}}参数成为我们的p_decorate
函数get_text
函数可以访问外部作用域,因此无论它想要什么,都可以使用func_wrapper
(又名func
}。但它如何知道get_text
的{{1}}参数?此外,它在哪里得到这个论点(因为它没有抱怨缺少name
)?毕竟,我们不会将其提供给get_text
。答案 0 :(得分:0)
在这种情况下,name
将成为传递给函数的参数。在其他情况下,如果我们对该函数了解不多,我们可以使用*args
和**kwargs
,在装饰器中有name
。实际上存在一个非常简洁的解释here。