Python 数据结构 – 数组和列表

avatar 2022年2月28日18:13:58 评论 260 次浏览

# 用魔法方法实现一个数组
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()
avatar

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: