印出回傳型別
你正在偵錯一個和朋友一起開發的套件。某個函式回傳的資料有點怪,但你還不確定是哪一個函式惹的禍。你知道有時候當你預期某個函式會回傳某種東西,結果卻回傳了別的東西,這樣的錯誤就會悄悄混進程式碼。例如,你預期函式回傳的是 numpy 陣列,但實際上回傳了 list,就可能出現非預期的行為。為了確認問題不是出在這裡,你決定寫一個裝飾器 print_return_type(),在它所裝飾的任何函式每次被呼叫並回傳時,都會把回傳變數的型別印出來。
本練習屬於課程
Python 函式寫作
練習說明
- 建立一個巢狀函式
wrapper(),它將成為新的被裝飾後的函式。 - 呼叫被裝飾的函式。
- 回傳這個新的被裝飾後的函式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def print_return_type(func):
# Define wrapper(), the decorated function
____ ____(____, ____):
# Call the function being decorated
result = ____(____, ____)
print('{}() returned type {}'.format(
func.__name__, type(result)
))
return result
# Return the decorated function
return ____
@print_return_type
def foo(value):
return value
print(foo(42))
print(foo([1, 2, 3]))
print(foo({'a': 42}))