理解这两个装饰器之间的区别

时间:2015-12-08 04:09:01

标签: python function python-2.7 decorator python-decorators

Python新手并尝试理解这两个装饰器之间的区别,其中装饰器A将其装饰的函数作为其参数,装饰器B似乎将装饰函数传递给自身内部的函数。

装饰者A:

def my_decorator(some_function):

  def wrapper():

      print "Something is happening before some_function() is called."

      some_function()

      print "Something is happening after some_function() is called."

  return wrapper

@ my_decorator
def just_some_function():
  print "Wheee!"

将产生:

Something is happening before some_function() is called.
Wheee!
Something is happening after some_function() is called.
None

装饰师B:

def decorator_factory(enter_message, exit_message):

    def simple_decorator(f):
        def wrapper():
            print enter_message
            f()
            print exit_message
        return wrapper
    return simple_decorator

@decorator_factory("Start", "End")
def hello():
    print "Hello World"

将产生:

Start
Hello World
End
None

我理解装饰师A是如何将some_function()传递给def wrapper()因为my_decorator()some_function作为其参数。

但是,对于装饰师B,当simple_decorator(f)正在def hello()f时,decorator_factory()如何收到"start""End")返回的值{1}}作为参数而不是def hello()? Python如何“知道”看似自动将def hello()传递给simple_decorator()

4 个答案:

答案 0 :(得分:2)

装饰器相当于包装它装饰的功能。

你的例子

@decorator_factory("Start", "End")
def hello():
    print "Hello World"

hello()

相同
def hello():
    print "Hello World"

hello = decorator_factory("Start", "End")(hello)

hello()

答案 1 :(得分:1)

装饰者A

@ my_decorator
def just_some_function():

等于:

just_some_function = my_decorator(just_some_function)

装饰者B

@decorator_factory("Start", "End")
def hello():

等于

hello = decorator_factory("Start", "End")(hello)

因为它在被使用之前被调用了一次,所以它更深了一步

答案 2 :(得分:1)

@decorator
def foo():
    ...

只是

的语法糖
def foo():
    ...

foo = decorator(foo)

因此

@decorator_factory(...)
def hello():
    ...

相当于

def hello():
    ...

hello = decorator_factory(...)(hello)

当然等同于

def hello():
    ...

decorator = decorator_factory(...)
hello = decorator(hello)

答案 3 :(得分:0)

所以没有人能正确回答你的问题:你想知道装饰师B simple_decorator如何得到函数f,因为decorator_factory会返回simple_decorator函数如此:decorator_factory("Start", "End")(hello)实际上等同于simple_decorator(hello)(你好是你的f

P.S。您可以在评论中找到有关2组参数的问题的答案。