Reputation: 290
def myfunc():
print(" myfunc() called.")
return 'ok'
The 'ok' was function's returned value.
>>> myfunc()
myfunc() called.
'ok'
Now to decorate it with other function. The decorate function.
def deco(func):
def _deco():
print("before myfunc() called.")
func()
print(" after myfunc() called.")
return _deco
To decorate myfunc with deco function.
@deco
def myfunc():
print(" myfunc() called.")
return 'ok'
>>> myfunc()
before myfunc() called.
myfunc() called.
after myfunc() called.
Why the result is not as following?
>>> myfunc()
before myfunc() called.
myfunc() called.
'ok'
after myfunc() called.
Upvotes: 1
Views: 62
Reputation: 20448
If you call the undecorated myfunc
function in the shell, it prints the returned value automatically. After the decoration, myfunc
is set to the _deco
function which only returns None
implicitly and doesn't print the returned value of myfunc
, so 'ok'
doesn't appear in the shell anymore.
If you want to print 'ok'
, you have to do it in the _deco
function:
def deco(func):
def _deco():
print("before myfunc() called.")
returned_value = func()
print(returned_value)
print(" after myfunc() called.")
return _deco
And if you want to return the value you have to return it from _deco
:
def deco(func):
def _deco():
print("before myfunc() called.")
returned_value = func()
print(" after myfunc() called.")
return returned_value
return _deco
Upvotes: 1