包接口
包接口的以下操作很有用:知道一个包是否为空,用一次操作就清空一个包,判断一个给定的项是否在包中,以及查看包中的每一项而不用清空包等等。
用户的包操作 | Bag类中的方法 |
---|---|
b = <class name>(<optional collection>) | __init__(self,sourceCollection = None) |
b.isEmpty() | isEmpty(self) |
len(b) | __len__(self) |
str(b) | __str__(self) |
item in b | __contains__(self,item); 如果包含了__iter__,就不需要该方法 |
b1 + b2 | __add__(self,other) |
b == anyObject | __eq__(self,other) |
b.clear() | clear(self) |
b.add(item) | add(self,item) |
b.remove(item) | remove(self,item) |
开发一个基于数组的实现
由于这是一个基于数组的实现,所以ArrayBag类型的每一个对象,都包含了该包中的一个数组。这个数组可以是已经实现的Array类的一个实例,也可以是另一个基于数组的集合(例如Python的list类型)。
Array类
"""
File: arrays.py
An Array is a restricted list whose clients can use
only [], len, iter, and str.
To instantiate, use
<variable> = array(<capacity>, <optional fill value>)
The fill value is None by default.
"""
class Array(object):
"""Represents an array."""
def __init__(self, capacity, fillValue = None):
"""Capacity is the static size of the array.
fillValue is placed at each position."""
self._items = list()
for count in range(capacity):
self._items.append(fillValue)
def __len__(self):
"""-> The capacity of the array."""
return len(self._items)
def __str__(self):
"""-> The string representation of the array."""
return str(self._items)
def __iter__(self):
"""Supports iteration over a view of an array."""
return iter(self._items)
def __getitem__(self, index):
"""Subscript operator for access at index."""
return self._items[index]
def __setitem__(sel