-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtrem_iter.py
More file actions
47 lines (32 loc) · 797 Bytes
/
trem_iter.py
File metadata and controls
47 lines (32 loc) · 797 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
"""
Um trem é um iterável com vagões.
O construtor pede o número de vagões::
>>> t = Trem(3)
O trem é um iterável::
>>> it = iter(t)
E o iterador obtido devolve vagões::
>>> next(it)
'vagão #1'
>>> next(it)
'vagão #2'
>>> next(it)
'vagão #3'
Somente a quantidade correta de vagões é devolvida::
>>> next(it)
Traceback (most recent call last):
...
StopIteration
Finalmente, podemos percorrer um trem num laço ``for``::
>>> for vagao in Trem(3):
... print(vagao)
...
vagão #1
vagão #2
vagão #3
"""
class Trem:
def __init__(self, qt_vagoes):
self.qt_vagoes = qt_vagoes
def __iter__(self):
for i in range(self.qt_vagoes):
yield 'vagão #{}'.format(i + 1)