2015-02-07 52 views
0

首先,這是我正在做的一項家庭作業任務,但我真的只是需要關於錯誤的幫助。調用一個類進行測試 - Python

因此,該項目是使用Array類實現一個向量(除了該項目名稱外的所有列表)。我正在使用的數組類可以找到here

我的錯誤是,每次我試圖打電話給我的代碼的時間來測試它,特別是的GetItemsetitem功能,在我結束一個錯誤,指出:

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 

除了不會導致錯誤之外,看起來沒有其他的做法。

+0

也許你只想使用'list'而不是那個Array類? – nbro 2015-02-07 19:51:12

回答

2

您需要創建Vector類的實例。嘗試:

vector = Vector() 
vector[0] = 42 

的錯誤意味着你正在嘗試錯誤地分配給Vector類本身,這並沒有太大的意義。

0

嘗試使用替換方法而不是分配值。

0

Vector是一類; Vector()創建該類的一個實例。

所以

Vector[i] = item 

給出一個錯誤:Vector.__setitem__是一個實例方法(針對類的一個實例運行時,即,對象),而不是一個類方法(針對一個類中運行)。 (理論上你可以使它成爲一個類方法,但我有麻煩想象一個用情況下,將是有意義的。)

在另一方面,

Vector()[i] = item 

# 1. creates a Vector() object 
# 2. calls {new_object}.__setitem__(self, i, item) 
# 3. doesn't keep any reference to {new_object}, so 
#  (a) you have no way to interact with it any more and 
#  (b) it will be garbage-collected shortly. 

嘗試

v = Vector() 
v[i] = item 

print(item in v) # => True