Python 数据结构 - 数组和列表

数组

# 用魔法方法实现一个数组
class Array:

    def __init__(self,size=30):
        self._size = size
        self._items = [None] * size

    def __getitem__(self,index):
        return self._items[index]

    def __setitem__(self,index,value):
        self._items[index] = value

    def __len__(self):
        return self._size

    def clear(self,value= None):
        for i in range(len(self._items)):
            self._items[i] = value

    def __iter__(self):
        for item in self._items:
            yield item

def test_array():
    size = 10
    a = Array(size)
    a[0] =1
    assert a[0] ==1
    print(a[0])


    a.clear()

    assert a[0] is None

test_array()

你可能感兴趣的:(Python,数据结构)