-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtrem.py
More file actions
59 lines (40 loc) · 1.03 KB
/
trem.py
File metadata and controls
59 lines (40 loc) · 1.03 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
"""
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):
return IteradorTrem(self)
class IteradorTrem:
def __init__(self, trem):
self.qt_vagoes = trem.qt_vagoes
self.vagao_atual = 0
def __next__(self):
self.vagao_atual += 1
if self.vagao_atual > self.qt_vagoes:
raise StopIteration()
return 'vagão #{}'.format(self.vagao_atual)