2017-09-08 66 views
1
def myfunc(): 
    print(" myfunc() called.") 
    return 'ok' 

'ok'是函数的返回值。函数的返回值在被其他函数装饰后丢失

>>> myfunc() 
myfunc() called. 
'ok' 

现在来装饰它与其他功能。 装饰功能。

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

用deco函数来装饰myfunc。

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

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

为什么结果不如下?

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

回答

1

如果调用未修饰myfunc功能的外壳,它会自动打印出返回的值。装饰之后,myfunc设置为_deco函数,该函数仅隐式返回None,并且不打印返回值myfunc,因此'ok'不再出现在shell中。

如果你想打印'ok',你必须这样做,在_deco功能:

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

如果你想返回值,你必须从_deco返回它:

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