I'm trying to create a class that inherits methods from a Python list, but also does some extra things on top ... maybe it's easier to just show the code at this point ...
class Host(object): """Emulate a virtual host attached to a physical interface""" def __init__(self):
My problem is that ... if I want to run the same object access tests on insert()
, as it was on append()
, I cannot find a way to code new methods without sacrificing support for one list expansion method ( i.e. list.append()
, list.insert()
or list.extend()
). If I try to support them all, I end up in recursive loops. What is the best way to solve this problem?
EDIT: I accepted the proposal for subclass collections. MutableSequence instead of Python () list
The resulting code ... posting here in case this helps someone ...
from collections import MutableSequence class HostList(MutableSequence): """A container for manipulating lists of hosts""" def __init__(self, data): super(HostList, self).__init__() if (data is not None): self._list = list(data) else: self._list = list() def __repr__(self): return "<{0} {1}>".format(self.__class__.__name__, self._list) def __len__(self): """List length""" return len(self._list) def __getitem__(self, ii): """Get a list item""" return self._list[ii] def __delitem__(self, ii): """Delete an item""" del self._list[ii] def __setitem__(self, ii, val):
source share