gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:40:00 34 4
gpt4 key购买 nike

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" 作为参数而不是 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()

关于python - 了解这两个装饰器之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34147834/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com