I'm not sure this title is good. Hope someone can help change it.
I am trying to define a class moleculeand hope that it can iterate over its atoms. I was looking for how people define an iterable class, and might look like this:
class molecule(object):
def __init__(self,name):
self.__pointer=0
def __iter__(self):
self.__pointer=0
return self
def __next__(self):
self.__pointer+=1
if self.__pointer<=self.natoms:
return self[self.__pointer]
else:
raise StopIteration("Exceeded all atoms")
It works well:
>>> ben=molecule('ben')
>>> ben.addatom(...)
>>> ite=iter(ben)
>>> for atom in ite:
... print(atom)
...
However, I found that it cannot work in two iterators if they exist simultaneously.
>>> ite=iter(ben)
>>> next(ite)
>>> next(ite)
>>> ite2=iter(ben)
>>> next(ite)
>>> next(ite2)
This is not surprising because the two iterators have the same one self.__pointer, so defining a new iterator will update the pointer to zero.
?, self.__pointer , .
, pointer (ite ite2), (molecule), .
, - :) .