首先,這是我正在做的一項家庭作業任務,但我真的只是需要關於錯誤的幫助。調用一個類進行測試 - Python
因此,該項目是使用Array類實現一個向量(除了該項目名稱外的所有列表)。我正在使用的數組類可以找到here。
我的錯誤是,每次我試圖打電話給我的代碼的時間來測試它,特別是的GetItem和setitem功能,在我結束一個錯誤,指出:
builtins.TypeError: 'type' object does not support item assignment
下面是類我目前正在建設,(到目前爲止,似乎只有len和包含正在工作)。
class Vector:
"""Vector ADT
Creates a mutable sequence type that is similar to Python's list type."""
def __init__(self):
"""Constructs a new empty vector with initial capacity of two elements"""
self._vector = Array(2)
self._capacity = 2
self._len = 0
def __len__(self):
"""Returns the number of items in the vector"""
return self._len
def __contains__(self, item):
"""Determines if the given item is stored in the vector"""
if item in self._vector:
return True
else:
return False
def __getitem__(self, ndx):
"""Returns the item in the index element of the list, must be within the
valid range"""
assert ndx >= 0 and ndx <= self._capacity - 1, "Array subscript out of range"
return self._vector[ndx]
def __setitem__(self, ndx, item):
"""Sets the elements at position index to contain the given item. The
value of index must be within a valid range"""
assert ndx >= 0 and ndx <= self._capacity - 1, "Array subscript out of range"
self._vector[ndx] = item
def append(self, item):
"""Adds the given item to the list"""
if self._len < self._capacity:
self._vector[self._len] = item
self._len += 1
我想無論是通過打字來調用代碼:
Vector()[i] = item
或
Vector[i] = item
然而,嘗試:
Vector[i] = item
給我的錯誤,和:
Vector()[i] = item
除了不會導致錯誤之外,看起來沒有其他的做法。
也許你只想使用'list'而不是那個Array類? – nbro 2015-02-07 19:51:12