Python Abstract Base Classes for Containers

PythonProgrammingServer Side Programming

There are some abstract base classes for the Python containers. There are different abstract base classes. These classes are like Containers, Hashtable, Generator, Set, MutableSet, Awaitable etc.

To use this module, we should import it using −

import collections.abc

Some Abstract Base Classes are there, which are very useful. These classes are used to develop different container classes. For an example we can create a container which has full set functionality. To make that, we can use the Set Abstract base class. We need to supply some methods in our class. These are __contains__(), __iter__() and the __len__()

Example Code

import collections.abc
class ListSet(collections.abc.Set):
   def __init__(self, iterable):
      self.elements = lst = list()
      for element in iterable:
      if element not in lst:
      lst.append(element)

   def __iter__(self):
      return iter(self.elements)

   def __contains__(self, value):
      return value in self.elements

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

   set1 = ListSet('ABCDEF')
   set2 = ListSet('DEFGHI')
   intersect = set1 & set2

   intersect_iter = iter(intersect)

try:
   while True:
   print(next(intersect_iter))
   except:
   pass

Output

D
E
F
raja
Published on 31-Oct-2018 11:31:40
Advertisements