我写了自己的List
类,它包装了另一个类似list
的数组类型。阵列具有固定容量,当阵列满时,我希望容量自动加倍。例如,如果我的基本容量是5,那么当数组已满并且添加另一个项目时,在添加项目之前,它将容量加倍为10。在类[python]中创建动态数组
这里是我的代码:
from referential_array import build_array
class List:
def __init__(self,capacity):
assert capacity >0, "Capacity cannot be negative"
self.count = 0
self._array = build_array(capacity)
self.capacity = capacity
def append(self,item):
has_space_left = not self.is_full()
if has_space_left:
self._array[self.count] = item
self.count+=1
else: #Issue here
create_more_space = List.__init__(self,capacity*2) #if list is full, capacity *2
self.count+=1
if __name__== "__main__":
myList = List(6)
myList.append(4)
myList.append(7)
myList.append(1)
myList.append(3)
myList.append(2)
myList.append(17)
myList.append(18)
myList.append(20)
下面
,第一我指定的大小为6。然后我继续追加超过600项以上。右边,当python看到没有空间时,容量会翻倍,因此18和20也可以被附加。
我收到一个错误,说容量没有在追加函数中定义。我试图让输出是:
4
7
1
3
2
17
18
20
单独使用'self.capacity'而不是'capacity'。但是我觉得在你的代码中还有其他问题只是看着它... – Julien
它没有被定义,因为你必须通过'self.capacity'来访问'capacity'。另外,你正在尝试做的事情是用你附加的所有东西来覆盖'_array'。 – Unatiel