# Module 08#

## Solution to Exercise 1: Iterators and generators#

# Using __iter__ and __next__
class range2:
def __init__(self, max_counter):
self.max_counter = max_counter
self.counter = 0

def __iter__(self):
return self

def __next__(self):
if self.counter < self.max_counter:
counter = self.counter
self.counter += 1
return counter
else:
raise StopIteration
# Testing it
print(range2(10))
print(tuple(range2(10)))
for i in range2(10):
print(i)
<__main__.range2 object at 0x7fc3c4ea4640>
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
0
1
2
3
4
5
6
7
8
9
# Using yield
def range3(max_counter):
counter = 0
while counter < max_counter:
yield counter
counter += 1
# Testing it
print(range3(10))
print(tuple(range3(10)))
for i in range3(10):
print(i)
<generator object range3 at 0x7fc3c4e9e120>
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
0
1
2
3
4
5
6
7
8
9

def __init__(self):
pass

def process(self):

class DataCleaner:
def __init__(self):
pass

def process(self):
print("I am cleaning some data")
class Pipeline:
def __init__(self):
self.modules = []

self.modules.append(module)
return self

def process(self):
print("I'm a pipeline, don't do anything much by myself")
for module in self.modules:
module.process()
p = Pipeline()