How would I create a custom list class in python?

后端 未结 5 1399
一个人的身影
一个人的身影 2020-12-14 16:25

I would like to write a custom list class in Python (let\'s call it MyCollection) where I can eventually call:

for x in myCollectionInstance:
           


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 16:54

    I like to subclass MutableSequence, as recommended by Alex Martelli. This works well for me, particularly when I need to add custom methods on top of the list I'm building.

    try:
        # Python 3
        from collections.abc import MutableSequence
    except ImportError:
        # Python 2.7
        from collections import MutableSequence
    
    class MyList(MutableSequence):
        """A container for manipulating lists of hosts"""
        def __init__(self, data=None):
            """Initialize the class"""
            super(MyList, 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)
            self._list[ii] = val
    
        def __str__(self):
            return str(self._list)
    
        def insert(self, ii, val):
            # optional: self._acl_check(val)
            self._list.insert(ii, val)
    
        def append(self, val):
            self.insert(len(self._list), val)
    
    if __name__=='__main__':
        foo = MyList([1,2,3,4,5])
        foo.append(6)
        print foo  # 
    

提交回复
热议问题