我试着使用装饰,发现他们有点酷,但我不完全明白里面发生了什么。让我们假设一个简单的例子,我借用了其中一页关于decorators的内容
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
参数是从哪里来的?我将描述我是如何理解这个过程的
name
参数的get_text
函数func
参数创建装饰函数p_decorate
,这个参数显然就是我们的get_text
函数p_decorate(get_text)
时,p_decorate
的func
参数就变成了get_text
函数func_wrapper
函数可以访问外部作用域,因此它可以根据需要处理func
(又称get_text
)。但是它怎么知道name
的get_text
参数呢?此外,它从哪里得到这个论点(因为它不抱怨name
的缺失)?毕竟,我们不把它提供给get_text
李>
在本例中,
name
将成为传递给函数的参数。在其他情况下,如果我们对函数了解不多,我们可以使用*args
和**kwargs
,其中您的decorator中有name
。一个相当简洁的解释实际上存在于here相关问题 更多 >
编程相关推荐