開始使用免費開始

檢查回傳型別

Python 對於資料型別的彈性常被視為這個語言的一大優點。不過,若是不正確的型別沒有被發現,有時也會造成問題。你決定為了確保程式碼確實照你的預期執行,要在所有函式中明確檢查回傳型別,並確認回傳值符合你的期望。為此,你將建立一個裝飾器,用來檢查被裝飾函式的回傳型別是否正確。

注意:assert 是一個關鍵字,可用來測試某件事是否為真。若你寫 assert conditionconditionTrue,這個語句不會做任何事。若 conditionFalse,則會拋出錯誤。它所拋出的錯誤型別為 AssertionError

本練習屬於課程

Python 函式寫作

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def returns_dict(func):
  # Complete the returns_dict() decorator
  def wrapper(____):
    result = ____
    assert type(result) == dict
    return result
  ____
  
@returns_dict
def foo(value):
  return value

try:
  print(foo([1,2,3]))
except AssertionError:
  print('foo() did not return a dict!')
  
編輯並執行程式碼