[英]python decorator and wrapper function debug
I'm studying the decorator and the wrapper by experimenting examples and I found the behavior of decorator that I can't understand. 我正在通过实验示例研究装饰器和包装器,发现装饰器的行为我无法理解。
def decorator_function(original_function):
def wrapper_function():
print "wrapper is executed before {}".format(original_function.__name__)
return original_function() # Try it without ()
return wrapper_function
@decorator_function
def display():
print("display function ran!")
when I run above function: 当我运行上面的函数时:
In [59]: display()
wrapper is executed before display
display function ran!
However, when I move the print function outside of the wrapper, it seems the wrapper doesn't run at all. 但是,当我将打印功能移到包装器之外时,包装器似乎根本没有运行。 (Probably it ran but I don't see the evidence.)
(可能已运行,但我看不到证据。)
def decorator_function(original_function):
def wrapper_function():
#print "wrapper is executed before {}".format(original_function.__name__)
return original_function() # Try it without ()
print "wrapper is executed before {}".format(original_function.__name__)
return wrapper_function
@decorator_function
def display():
print("display function ran!")
Then I don't see "wrapper is executed before..." anymore. 然后,我不再看到“包装器在...之前执行过”。 How come?
怎么会? What am I missing here?
我在这里想念什么?
In [63]: display()
display function ran!
The decorator executes when your code loads , while the wrapper executes when your code runs . 装饰器在代码加载时执行,而包装器在代码运行时执行 。 If I dump your second example into a file
example.py
and run it like this: 如果我将您的第二个示例转储到文件
example.py
并像这样运行它:
pythohn -i example.py
I see: 我懂了:
wrapper is executed before display
>>>
That was the decorator running. 装饰器正在运行。 Now if I call
display()
, I see the output from that function: 现在,如果我调用
display()
,我将看到该函数的输出:
>>> display()
display function ran!
>>>
I don't see the output from the decorator here because it already ran . 我在这里看不到装饰器的输出,因为它已经运行了 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.