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!" and not the two wrappers?
Here you are evaluating print_text
(thus printing "Hello World!"), and passing the result to decor
:
decor(print_text())
Here we are passing print_text
to decor
, and calling the resulting function which it returns, which is wrap
::
decor(print_text)()
Notice that the first case will NOT call the function returned from decor
. Try to call it and see what happens:
decor(print_text())()
TypeError: 'NoneType' object is not callable
because func
is now None
.
That is because you only return the function wrap - It is not called. If you do call it, either by assigning the result to a variable, or by using decor(print_text)()
directly. 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. 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. That argument is whatever print_text()
returns. Well, print_text()
prints something and then returns None. So far, your output is just Hello world!
. None is now passed to decor
, and it returns the wrap()
function. Nowhere is wrap()
actually called, and your final output is just 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.