用python装饰装饰器

Codenobar

我无法理解装饰装饰器在Python(2.7.2)中的工作方式。我有以下一段代码:

def verbose(function):
    print 'i am verbose and func is ' + function.__name__
    def wrapper2(func):
        print 'func is ' + repr(func)
        result = function(func)
        return result
    return wrapper2

@verbose
def more(function):
    print 'i am more and func is ' + function.__name__
    def wrapper1(*args, **kwargs):
        print 'args' + repr(args)
        result = function(*args)
        return result
    return wrapper1

@more
def hello(*args):
    print(sum(args))

当我跑步时:

>>> hello(1,2,3)

这是我得到的:

i am verbose and func is more
func is <function hello at 0x1015338c0>
i am more and func is hello    
args(1, 2, 3)
6

我无法可视化生成此输出的调用顺序。我认为以下调用仍将生成相同的输出,并且我很想了解装饰装饰器在此特定示例中的工作方式。

>>> verbose(more)(hello)(1,2,3)
i am verbose and func is more
func is <function hello at 0x101533d70>
i am more and func is hello
args(1, 2, 3)
6
布伦·巴恩

您对的减少verbose(more)(hello)(1,2,3)是正确的。但是,这些呼叫发生在不同的时间。请记住,这是:

@deco
def func():
    # whatever

与此相同:

def func():
    # whatever
func = deco(func)

因此,当您定义时more,将verbose被调用。定义时hellomore将调用(修饰后的版本)。您的代码等效于:

def verbose(function):
    print 'i am verbose and func is ' + function.__name__
    def wrapper2(func):
        print 'func is ' + repr(func)
        result = function(func)
        return result
    return wrapper2

def more(function):
    print 'i am more and func is ' + function.__name__
    def wrapper1(*args, **kwargs):
        print 'args' + repr(args)
        result = function(*args)
        return result
    return wrapper1
more = verbose(more)

def hello(*args):
    print(sum(args))
hello = more(hello)

那应该清楚什么时候发生哪个函数调用。请注意,呼叫moreverbose都不被呼叫 hello(1, 2, 3)装饰器是在定义装饰函数时调用的,而不是在调用装饰函数时调用的。在调用时,称为装饰器的返回值(即,函数wrapper1wrapper2您的示例中的返回值)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章