1

I have a class called ObjectSet that I want to be iterable. It resets my "pointer" after a for loop but not if I break the loop.

My class ObjectSet has the methods defined in the attached code. I loop through an object set and when I find a particular object, i break the loop, but I don't know how to reset the pointer in this case in a good way.

class ObjectSet:

   def __init__(self,objects = None):
      if not objects: self.objects = []
      else: self.objects = objects
      self.pointer = 0
   def __iter__(self):
      return self
   def __len__(self):
      return len(self.objects)
   def __next__(self):
      cur_pointer = self.pointer
      if cur_pointer >= len(self):
         self.pointer = 0
         raise StopIteration
      self.pointer += 1
      return self.objects[cur_pointer]


objs = ObjectSet([1,2,3])
for obj in objs:
   if obj == 2:
      break
for obj in objs:
   print(obj)

The code only prints 3, but I want it to print 1,2, and 3, as it does with a list.

  • the answer to the proposed duplicate https://stackoverflow.com/questions/21665485/how-to-make-a-custom-object-iterable is exactly the code as presented in this question... – hiro protagonist Oct 30 '19 at 11:14
  • Thanks for pointing out the duplicate, I missed that one. – Anton Fahlgren Oct 30 '19 at 13:33
  • i did not mean to tell you that there is a duplicate; quite the opposite. someone had closed your question with the link above as duplicate. i reopened it because the **answer** there is your **question** (and will not work in your case). – hiro protagonist Oct 30 '19 at 15:59

1 Answers1

1

you could implement the iterator pattern.

but given that your basic data structure supports iteration already you could just do this:

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

(and remove the __next__ method and self.pointer from your class).

the problem with your design is that there is only one self.pointer per instance of your class ObjectSet. but as you noticed only the iterator you return should remember the next position. that is what the iterator pattern would do for you.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111