Implement a custom container types

Want to implement a custom class that mimic the common built-in container types (such as list or dict) behavior. However, unsure which method to achieve.

collections.abc module defines various abstract base class, custom container class is useful in achieving these base classes. Usually custom class by inheriting the base class corresponding to the module, then the required method implementation class. as follows:

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__ 
>>>

Corresponding method defined in the base class inherits the base class is not simple to achieve, still the subclasses of abstract type, not initialize an object instance operations. Thus, Iterable the __iter__ Method A class must implement.

If you want to know which base class subclasses implement need to be tested directly to the base class, the base class is instantiated as initialization, view exception information, as follows:

>>> 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__
>>>

From the above, if a subclass inherits from Sequence, you will need to achieve its __getitem__ and __len__ method.

The following examples explain this mechanism:

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)

Guess you like

Origin www.cnblogs.com/jeffrey-yang/p/12131029.html