Two examples of iteration support in a user-defined class in Python.
Example 1.
The container class is used with for..in statement:
class Experiment:
def __init__(self):
self.q = [1, 2, 3, 4, 5]
self.lent = len(self.q)
self.inn = 0
def __iter__(self):
return self
def __next__(self):
if self.inn == self.lent:
raise StopIteration
x = self.q[self.inn]
self.inn += 1
return x
ob = Experiment()
for ind in ob:
print(ind)
run it and get:
1
2
3
4
5
Example 2.
Iterator defined in the class is used with for..in statement:
class Experiment:
def __init__(self):
self.q = [1, 2, 3, 4, 5]
self.lent = len(self.q)
self.inn = 0
def __iter__(self):
return self
def __next__(self):
if self.inn == self.lent:
raise StopIteration
x = self.q[self.inn]
self.inn += 1
return x
ob = Experiment()
itr = iter(ob)
for ind in itr:
print(ind)
the result is the same as above:
1
2
3
4
5
Comments
Post a Comment