t476.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. class Counter:
  2. class CounterIter:
  3. def __init__(self, c):
  4. self.c = c
  5. self.idx = 0
  6. def __iter__(self):
  7. return self
  8. def next(self):
  9. n = self.idx
  10. self.idx += 1
  11. if n > self.c.stop:
  12. raise StopIteration
  13. return n
  14. def __init__(self, stop):
  15. self.count = 0
  16. self.stop = stop
  17. self.dict = {}
  18. def __iter__(self):
  19. return self.CounterIter(self)
  20. def __len__(self):
  21. return self.count
  22. def __repr__(self):
  23. return "< Counter Object: ("+str(self.count)+","+str(self.stop)+") >"
  24. def __str__(self):
  25. return "("+str(self.count)+","+str(self.stop)+")"
  26. def __call__(self, x):
  27. for i in range(x):
  28. if i % 2 != 0:
  29. continue
  30. self.dict[i] = i + 1
  31. def __getitem__(self, key):
  32. if key in self.dict:
  33. return self.dict[key]
  34. return -1
  35. def __setitem__(self, key, value):
  36. self.dict[key] = value
  37. a = Counter(10)
  38. for x in a:
  39. print x
  40. print len(a)
  41. print a, str(a), repr(a)
  42. a(20)
  43. print a[5], a[8], a[30]
  44. a[30] = 'thirty'
  45. print a[30]
  46. b = Counter(5)
  47. c = Counter(5)
  48. print
  49. print list(b)
  50. print sum(c)
  51. print b.__len__()
  52. print b.__str__()
  53. print b.__repr__()
  54. b.__call__(10)
  55. print b.__getitem__(4)
  56. print b.__getitem__(15)
  57. b.__setitem__(15, 'hello')
  58. print b.__getitem__(15)