实现自定义容器类型

想要实现一个自定义类,该类模仿普通的内置容器类型(例如list或dict)的行为。 但是,不确定要实现哪种方法。

collections.abc模块定义了各种抽象基类,这些基类在实现自定义容器类时非常有用。自定义类一般通过继承该模块的对应基类,然后实现所需要的类方法。如下:

from collections.abc import Iterable

class A(Iterable):
    pass

>>> a = A()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class A with abstract methods __iter__ 
>>>

简单的继承基类却不实现基类中定义的相应方法,则子类仍为抽象类型,无法进行初始化实例对象操作。因此,A类必须实现Iterable的__iter__方法。

如果想知道基类的哪些方法需要被子类实现,可以直接对基类进行测试,如对基类进行实例初始化,查看异常信息,如下:

>>> from collections.abc import Sequence
>>> Sequence()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Sequence with abstract methods __getitem__, __len__
>>>

由上可知,如果某个子类继承自Sequence,则需要实现其__getitem__和__len__方法。

下面的示例可以解释这种机制:

from collections.abc import Sequence
from bisect

class SortedItems(Sequence):
    def __init__(self, initial=None):
        self._items = sorted(initial) if initial is not None else []

    # Required sequence methods
    def __getitem__(self, index):
        return self._items[index]

    def __len__(self):
        return len(self._items)

    # Method for adding an item in the right location
    def add(self, item):
        bisect.insort(self._items, item)

猜你喜欢

转载自www.cnblogs.com/jeffrey-yang/p/12131029.html