-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtrem_seq.py
More file actions
53 lines (37 loc) · 966 Bytes
/
trem_seq.py
File metadata and controls
53 lines (37 loc) · 966 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
48
49
50
51
52
53
"""
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
Neste caso, cada vagão pode ser acessado por um índice:
>>> t[1]
'vagão #2'
"""
class Trem:
def __init__(self, qt_vagoes):
self.qt_vagoes = qt_vagoes
def __getitem__(self, indice):
if indice < self.qt_vagoes:
return 'vagão #{}'.format(indice + 1)
else:
raise IndexError('não há mais vagões')