The current wisdom recommends to inherit from collections.MutableSequence
instead of List
.
To make MutableSequence work, some methods have to be implemented:
__init__
or __new__
__getitem__
__setitem__
__delitem__
__len__
insert
One reason to implement this can be to ensure that the contents of the List have a specific type.
from collections import MutableSequence
class ListLike(MutableSequence):
'''
A Class that behaves like a List
'''
@staticmethod
def __checkValue(value):
if not isinstance(value, object):
raise TypeError()
I prefer to use __init__
and to set the container here.
def __init__(self):
self.__store = []
__getitem__
retrieves an item by index (this is a List, not a Directory).
def __getitem__(self, key):
'''
@param key: Index
@type key: L{int}
@return: Item at location index
'''
return self.__store[key]
__setitem__
assigns a new value at index.
def __setitem__(self, key, value):
'''
@param key: Index
@type key: L{int}
@param value: New Value
'''
self.__checkValue(value)
self.__store[key] = value
__delitem__
removes the item at index.
def __delitem__(self, key):
'''
@param key: Index
@type key: L{int}
'''
del self.__store[key]
__len__
returns the length of the list (number of entries).
def __len__(self):
return len(self.__store)
insert
adds an item at index.
def insert(self, key, value):
'''
@param key: Index
@type key: L{int}
@param value: New Value
'''
self.__checkValue(value)
self.__store.insert(key, value)
Complete Code to copy below:
from collections import MutableSequence
class ListLike(MutableSequence):
'''
A Class that behaves like a List
'''
@staticmethod
def __checkValue(value):
if not isinstance(value, object):
raise TypeError()
def __init__(self):
self.__store = []
def __getitem__(self, key):
'''
@param key: Index
@type key: L{int}
@return: Item at location index
'''
return self.__store[key]
def __setitem__(self, key, value):
'''
@param key: Index
@type key: L{int}
@param value: New Value
'''
self.__checkValue(value)
self.__store[key] = value
def __delitem__(self, key):
'''
@param key: Index
@type key: L{int}
'''
del self.__store[key]
def __len__(self):
return len(self.__store)
def insert(self, key, value):
'''
@param key: Index
@type key: L{int}
@param value: New Value
'''
self.__checkValue(value)
self.__store.insert(key, value)