2017-09-08 34 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