我正在尝试构建一个从
Python列表中继承方法的类,但也会在顶部做一些额外的事情……此时显示代码可能更容易……
class Host(object): """Emulate a virtual host attached to a physical interface""" def __init__(self): # Insert class properties here... pass class HostList(list): """A container for managing lists of hosts""" def __init__(self): self = [] def append(self,hostobj): """append to the list...""" if hostobj.__class__.__name__ == 'Host': self.insert(len(self),hostobj) else: _classname = hostobj.__class__.__name__ raise RuntimeError,"Cannot append a '%s' object to a HostList" % _classname
我的问题是这个……如果我想在insert()上执行与append()相同类型的对象许可测试,我找不到一种方法来编写新方法而不牺牲对一个列表的支持扩展方法(即list.append(),list.insert()或list.extend()).如果我试图全部支持它们,我最终会使用递归循环.解决这个问题的最佳方法是什么?
编辑:我采取了关于子类化collections.MutableSequence而不是Python的列表()的建议
由此产生的代码…发布在这里,以防万一…
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): # optional: self._acl_check(val) return self._list[ii] def __str__(self): return str(self._list) def insert(self,val): # optional: self._acl_check(val) self._list.insert(ii,val) def append(self,val): self.insert(len(self._list),val)