一. python数据结构与算法

class Bag(object):
    def __init__(self,maxsize=10):
        self.maxsize=maxsize
        self._item=list()
    def add(self,item):
        if len(self)>self.maxsize:
            raise Exception('bag is full')
        self._item.append(item)
    def remove(self,item):
        self._item.remove(item)
    def __len__(self):
        return len(self._item)
    def __iter__(self):
        for item in self._item:
            yield item

def test_bag():
    bag=Bag()

    bag.add(1)
    bag.add(2)
    bag.add(3)

    assert len(bag)==3
    bag.remove(3)

    assert len(bag)==2
    for i in bag:
        print(i)

test_bag()
posted @ 2019-09-05 17:43  培天王  阅读(152)  评论(0编辑  收藏  举报