base.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. """Some base classes inherited by others"""
  2. class BaseCollection(object):
  3. """Base class for everything"""
  4. def __init__(self):
  5. super(BaseCollection, self).__init__()
  6. def size(self):
  7. """This implementation works for almost every class in ODS"""
  8. return self.n
  9. def __len__(self):
  10. return self.size()
  11. def __str__(self):
  12. return "[" + ",".join([str(x) for x in self]) + "]"
  13. def __repr__(self):
  14. return self.__class__.__name__ \
  15. + "(["+ ",".join([repr(x) for x in self]) +"])"
  16. class BaseSet(BaseCollection):
  17. """Base class for Set implementations"""
  18. def __init__(self):
  19. super(BaseSet, self).__init__()
  20. def add_all(self, a):
  21. for x in a:
  22. self.add(x)
  23. def __in__(self, x):
  24. return self.find(x) is not None
  25. def __eq__(self, a):
  26. if len(a) != len(self): return False
  27. for x in self:
  28. if not x in a: return False
  29. for x in a:
  30. if not x in self: return False
  31. return True
  32. def __ne__(self, a):
  33. return not self == a
  34. class BaseList(BaseCollection):
  35. """Base class for List implementations"""
  36. def __init__(self):
  37. super(BaseList, self).__init__()
  38. def append(self, x):
  39. self.add(self.size(), x)
  40. def add_all(self, iterable):
  41. for x in iterable:
  42. self.append(x)
  43. def clear(self):
  44. """This can be overridden with more efficient implementations"""
  45. while self.size() > 0:
  46. self.remove(self.size()-1)
  47. def add_first(self, x):
  48. return self.add(0, x)
  49. def remove_first(self):
  50. return self.remove(0)
  51. def add_last(self, x):
  52. return self.add(self.size(), x)
  53. def remove_last(self):
  54. return self.remove(self.size()-1)
  55. def insert(i, x):
  56. self.add(i, x)
  57. def __iter__(self):
  58. """This implementation is good enough for array-based lists"""
  59. for i in range(len(self)):
  60. yield(self.get(i))
  61. def __eq__(self, a):
  62. if len(a) != len(self): return False
  63. it1 = iter(a)
  64. it2 = iter(self)
  65. for i in range(len(a)):
  66. if it1.next() != it2.next(): return False
  67. return True
  68. def __ne__(self, a):
  69. return not self == a
  70. def index(self, x):
  71. i = 0
  72. for y in self:
  73. if y == x:
  74. return i
  75. i += 1
  76. raise ValueError('%r is not in the list' % x)
  77. def remove_value(self, x):
  78. try:
  79. return self.remove(self.index(x))
  80. except ValueError:
  81. return False
  82. def __getitem__(self, key):
  83. return self.get(key)
  84. def __setitem__(self, key, value):
  85. return self.set(key, value)
  86. def __delitem__(self, i):
  87. self.remove(i)