我正在努力在Python中創建一個僞Vector
類,我想知道如果我應該錯誤檢查,如果是的話,在多大程度上。容器類是處理錯誤還是僅僅提高它們?
例如,當它下面的人:
vec = Vector(1,2,3,4)
# vec is now [1,2,3,4]
vec[100] = 12
應與IndexError
發生什麼由我__setitem__
產生的?如果我__setitem__
包含:
if index < 0 or index >= len(self.vector):
raise IndexError("Index out of bounds")
還是應
try:
if index < 0 or index >= len(self.vector):
raise IndexError("Index out of bounds")
except IndexError as e:
print(str(e))
是一般的情況下,一個容器類的用戶將處理錯誤,還是應該容器本身知道處理錯誤?
好吧,那就是我開始想的 –