加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

将list.insert()方法模拟为Python列表的子类

发布时间:2020-12-12 07:28:11 所属栏目:MsSql教程 来源:网络整理
导读:我正在尝试构建一个从 Python列表中继承方法的类,但也会在顶部做一些额外的事情……此时显示代码可能更容易…… class Host(object): """Emulate a virtual host attached to a physical interface""" def __init__(self): # Insert class properties here...
我正在尝试构建一个从 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)

解决方法

如果你可以避免它,不要继承内置类. (你可以,但这并不意味着你应该没有真正令人信服的理由)

这些类针对速度进行了优化,这使得从它们继承正确非常乏味,因为您最终必须覆盖几乎所有内容.

继承自collections.MutableSequence只允许您实现一些基本方法,并获得序列API的强大的全功能实现,没有从列表继承的所有怪癖和警告.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读