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.