Skip to main content
 首页 » 编程设计

Python之装饰器调用内部函数

2024年10月01日6sxdcgaq8080

我目前正在试用装饰器,但我无法理解一件事。我有简单的装饰器:

def new_decorator(func): 
    print "Calling new_decorator()" 
    def wrap(arg): 
        print "Calling wrap()" 
        func(arg) 
    return wrap   
 
@new_decorator 
def foo(name): 
    print name 

运行后我们得到:

'Calling decorate()'  

仅在调用 foo 之后:

>>> foo('Jon') 
Calling wrap() 
Jon 

到现在我都明白了(我想)。 new_decorator(func) 在一开始被调用,以 foo 作为参数,它返回 wrap。但现在我尝试了带参数的装饰器:

def add_attr(varname, value): 
    def decorate(func): 
        print "Calling decorate()" 
        setattr(func, varname, value) 
        return func 
    return decorate 
 
@add_attr('var', 'New attribute') 
def foo(): 
    print "Calling foo()" 
    print foo.var 

运行它时(不调用 foo())它返回:

'Calling decorate()' 

在 foo() 之后:

>>> foo() 
Calling foo() 
New attribute 

我不明白的是,为什么这个“内部”函数 decorate 在一开始就被调用,甚至在调用 foo 之前?在第一个例子中它不是。函数 foo 是如何作为参数发送给 decorate 的? add_attr 只得到2个参数,而且都不是foo。

请您参考如下方法:

对于接受参数的装饰器,通常需要 3 层嵌套。将接受参数的装饰器视为“装饰器制造商”。 它应该在被调用时返回一个装饰器。

要理解这一点,请考虑下面的代码

@new_decorator 
def foo(name): 
    print name 

真的只是语法糖:

def foo(name): 
    print name 
 
foo = new_decorator(foo) 

所以,类似地,这个:

@add_attr('var', 'New attribute') 
def foo(): 
    print "Calling foo()" 
    print foo.var 

与此相同:

def foo(): 
    print "Calling foo()" 
    print foo.var 
 
foo = add_attr('var', 'New attribute')(foo) 

这应该会指导您正确编写 add_attr 的正确方向。

如果您在尝试几次后仍然感到困惑,我建议您引用 a famous answer from e-satis这比我在网上看到的任何其他内容都更能解释装饰器。