Python 3.x 功能';s被其他函数修饰后返回的值丢失

Python 3.x 功能';s被其他函数修饰后返回的值丢失,python-3.x,python-decorators,Python 3.x,Python Decorators,“ok”是函数的返回值 def myfunc(): print(" myfunc() called.") return 'ok' 现在用其他功能来装饰它。 装饰功能 >>> myfunc() myfunc() called. 'ok' def deco(func): def _deco(): print("before myfunc() called.") func() print(" after

“ok”是函数的返回值

def myfunc():
    print(" myfunc() called.")
    return 'ok'
现在用其他功能来装饰它。 装饰功能

>>> myfunc()
 myfunc() called.
'ok'
def deco(func):
    def _deco():
        print("before myfunc() called.")
        func()
        print("  after myfunc() called.")
    return _deco
用装饰功能装饰myfunc

>>> myfunc()
 myfunc() called.
'ok'
def deco(func):
    def _deco():
        print("before myfunc() called.")
        func()
        print("  after myfunc() called.")
    return _deco
为什么结果不是这样

@deco
def myfunc():
    print(" myfunc() called.")
    return 'ok'

>>> myfunc()
before myfunc() called.
 myfunc() called.
  after myfunc() called.

如果在shell中调用未修饰的
myfunc
函数,它会自动打印返回值。装饰完成后,
myfunc
被设置为
\u deco
函数,该函数只隐式返回
None
,不打印
myfunc
的返回值,因此
'ok'
不再显示在shell中

如果要打印
“确定”
,必须在
\u deco
功能中执行:

>>> myfunc()
before myfunc() called.
 myfunc() called.
'ok'
  after myfunc() called.
如果要返回值,必须从
\u deco
返回:

def deco(func):
    def _deco():
        print("before myfunc() called.")
        returned_value = func()
        print(returned_value)
        print("  after myfunc() called.")
    return _deco