繁体   English   中英

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

[英]Understanding the difference between these two 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

我知道使用Decorator A可以将some_function()传递给def wrapper()因为my_decorator()some_function作为其参数。

但是对于装饰器B,当decorator_factory()"start""End"作为其参数而不是def hello()时, simple_decorator(f)接收def hello()返回的值(作为f def hello() Python如何看似自动将def hello()传递给simple_decorator()

装饰器等效于包装它装饰的功能。

你的例子

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

hello()

是相同的

def hello():
    print "Hello World"

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

hello()

装饰器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)

因为它在使用前被调用过一次,所以它要深一层

@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)

因此,没有人正确回答您的问题:您想知道在装饰器B中simple_decorator如何获取函数f ,这是因为decorator_factory返回了那个simple_decorator函数,所以: decorator_factory("Start", "End")(hello)实际上等效于simple_decorator(hello) (你好是你的f

PS:您可以在注释中找到有关2组参数的问题的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM