数组Array

2018-06-09 20:27:41 -0400
class Array(object):
    '''for example.
      >>> array = Array(6)
      >>> array.__len__()
      6
      >>> array.__setitem__(0,1)
      >>> array[1] = 2
      >>> array.__getitem__(0)
      1
      >>> array[1]
      2
      >>> for i in array:print(i)
      1
      2
      None
      None
      None
      None
      >>> array.clear()
      >>> array[::]
      [None, None, None, None, None, None]
    '''
    def __init__(self,size=32):
        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):
        for i in range(self.size):
            self._items[i] = None

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

def test_arr():
    array = Array(10)
    assert array.__len__() == 10
    array[0] = 1
    assert array[0] == 1
    array.clear()
    assert array[0] == None

if __name__ == '__main__':
    import doctest
    doctest.testmod()
«Newer      Older»
Comment:
Name:

Back to home

Subscribe | Register | Login | N