[英]Why doesn't wrap function in Python get executed when I call it?
I have this simple code. 我有这个简单的代码。
def decor(func):
def wrap():
print("============")
func()
print("============")
return wrap
def print_text():
print("Hello world!")
decor(print_text())
Why does this only print "Hello world!" 为什么只打印“ Hello world!” and not the two wrappers? 而不是两个包装?
Here you are evaluating print_text
(thus printing "Hello World!"), and passing the result to decor
: 在这里,您正在评估print_text
(因此打印“ Hello World!”),并将结果传递给decor
:
decor(print_text())
Here we are passing print_text
to decor
, and calling the resulting function which it returns, which is wrap
:: 在这里,我们将print_text
传递给decor
,并调用返回的结果函数,即wrap
::
decor(print_text)()
Notice that the first case will NOT call the function returned from decor
. 注意,第一种情况不会调用decor
返回的函数。 Try to call it and see what happens: 尝试调用它,看看会发生什么:
decor(print_text())()
TypeError: 'NoneType' object is not callable TypeError:“ NoneType”对象不可调用
because func
is now None
. 因为func
现在是None
。
That is because you only return the function wrap - It is not called. 那是因为您只返回函数wrap-不被调用。 If you do call it, either by assigning the result to a variable, or by using decor(print_text)()
directly. 如果确实要调用它,则可以将结果分配给变量,也可以直接使用decor(print_text)()
。 Note that you should use print_text
and not print_text()
, as the latter will give the result of the function to decor, rather than the function itself. 请注意,您应该使用print_text
而不是print_text()
,因为后者将使函数的结果进行print_text()
,而不是函数本身。 The working version would be: 工作版本为:
def decor(func):
def wrap():
print("============")
func()
print("============")
return wrap
def print_text():
print "Hello world!"
wrapped_function = decor(print_text)
wrapped_function()
You are calling decor
with a single argument. 您正在用单个参数调用decor
。 That argument is whatever print_text()
returns. 该参数是print_text()
返回的值。 Well, print_text()
prints something and then returns None. 好吧, print_text()
打印一些内容,然后返回None。 So far, your output is just Hello world!
到目前为止,您的输出仅仅是Hello world!
. 。 None is now passed to decor
, and it returns the wrap()
function. 现在没有任何内容传递给decor
,它返回wrap()
函数。 Nowhere is wrap()
actually called, and your final output is just Hello world!
wrap()
实际上没有调用,您的最终输出就是Hello world!
. 。
You are misunderstanding the use of decorators. 您误解了装饰器的使用。 The correct syntax is this: 正确的语法是这样的:
@decor
def print_text():
print("Hello world!")
That is a shortcut for this: 这是一个捷径:
def print_text():
print("Hello world!")
print_text = decor(print_text)
Now you can see that it is the returns of decor(print_text)
(the wrap()
function) that is being called, and everything is printed. 现在,您可以看到正在调用decor(print_text)
( wrap()
函数)的返回,并且所有内容decor(print_text)
打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.