-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterable_iterator.py
More file actions
50 lines (34 loc) · 949 Bytes
/
iterable_iterator.py
File metadata and controls
50 lines (34 loc) · 949 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class MyIterable:
def __init__(self, data):
self.data = data
def __iter__(self):
# return an iterator
return iter(self.data)
class MyIterable2:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
# return an item with the index
return self.data[index]
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
result = self.data[self.index]
self.index += 1
return result
if __name__=='__main__':
my_obj = MyIterable([1, 2, 3, 4])
for item in my_obj:
print(item)
my_obj2 = MyIterable2([1, 2, 3, 4])
for item in my_obj2:
print(item)
my_obj = MyIterator([1, 2, 3, 4])
for item in my_obj:
print(item)