1. import collections.abc
    2. import bisect
    3. class SortedItems(collections.abc.Sequence):
    4. def __init__(self, initial=None):
    5. self._items = sorted(initial) if initial is not None else []
    6. def __getitem__(self, index):
    7. return self._items[index]
    8. def __len__(self):
    9. return len(self._items)
    10. def add(self, item):
    11. bisect.insort(self._items, item)
    12. items = SortedItems([5, 1, 3])
    13. print(list(items))
    14. print(items[0], items[-1])
    15. items.add(2)
    16. print(list(items))
    1. [1, 3, 5]
    2. 1 5
    3. [1, 2, 3, 5]

    可以看到,SortedItems 跟普通的列表没什么两样,支持所有常用操作,包括索引、迭代、包含判断,甚至是切片操作。
    这里面使用到了 bisect 模块,它是一个在排序列表中插入元素的高效方式。可以保证元素插入后还保持顺序。

    1. >>> items = SortedItems()
    2. >>> import collections
    3. >>> isinstance(items, collections.Iterable)
    4. True
    5. >>> isinstance(items, collections.Sequence)
    6. True
    7. >>> isinstance(items, collections.Container)
    8. True
    9. >>> isinstance(items, collections.Sized)
    10. True
    11. >>> isinstance(items, collections.Mapping)
    12. False
    13. >>>

    collections 中很多抽象类会为一些常见容器操作提供默认的实现, 这样一来你只需要实现那些你最感兴趣的方法即可。假设你的类继承自 collections.MutableSequence ,如下:

    1. class Items(collections.MutableSequence):
    2. def __init__(self, initial=None):
    3. self._items = list(initial) if initial is not None else []
    4. # Required sequence methods
    5. def __getitem__(self, index):
    6. print('Getting:', index)
    7. return self._items[index]
    8. def __setitem__(self, index, value):
    9. print('Setting:', index, value)
    10. self._items[index] = value
    11. def __delitem__(self, index):
    12. print('Deleting:', index)
    13. del self._items[index]
    14. def insert(self, index, value):
    15. print('Inserting:', index, value)
    16. self._items.insert(index, value)
    17. def __len__(self):
    18. print('Len')
    19. return len(self._items)

    如果你创建 Items 的实例,你会发现它支持几乎所有的核心列表方法 (如 append ()、remove ()、count () 等)。 下面是使用演示:

    1. >>> a = Items([1, 2, 3])
    2. >>> len(a)
    3. Len
    4. 3
    5. >>> a.append(4)
    6. Len
    7. Inserting: 3 4
    8. >>> a.append(2)
    9. Len
    10. Inserting: 4 2
    11. >>> a.count(2)
    12. Getting: 0
    13. Getting: 1
    14. Getting: 2
    15. Getting: 3
    16. Getting: 4
    17. Getting: 5
    18. 2
    19. >>> a.remove(3)
    20. Getting: 0
    21. Getting: 1
    22. Getting: 2
    23. Deleting: 2
    24. >>>