From ecd23ea4c113a6cbeb48efe495c99e5a864460ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luiz=20Ot=C3=A1vio?= Date: Tue, 6 Dec 2022 10:52:25 -0300 Subject: [PATCH] =?UTF-8?q?Criando=20sua=20pr=C3=B3pria=20lista=20com=20It?= =?UTF-8?q?erable,=20Iterator=20e=20Sequence=20(collections.abc)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aula161.py | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 aula161.py diff --git a/aula161.py b/aula161.py new file mode 100644 index 0000000..e8c2650 --- /dev/null +++ b/aula161.py @@ -0,0 +1,54 @@ +# Implementando o protocolo do Iterator em Python +# Essa é apenas uma aula para introduzir os protocolos de collections.abc no +# Python. Qualquer outro protocolo poderá ser implementando seguindo a mesma +# estrutura usada nessa aula. +# https://docs.python.org/3/library/collections.abc.html +from collections.abc import Sequence + + +class MyList(Sequence): + def __init__(self): + self._data = {} + self._index = 0 + self._next_index = 0 + + def append(self, *values): + for value in values: + self._data[self._index] = value + self._index += 1 + + def __len__(self) -> int: + return self._index + + def __getitem__(self, index): + return self._data[index] + + def __setitem__(self, index, value): + self._data[index] = value + + def __iter__(self): + return self + + def __next__(self): + if self._next_index >= self._index: + self._next_index = 0 + raise StopIteration + + value = self._data[self._next_index] + self._next_index += 1 + return value + + +if __name__ == '__main__': + lista = MyList() + lista.append('Maria', 'Helena') + lista[0] = 'João' + lista.append('Luiz') + # print(lista[0]) + # print(len(lista)) + for item in lista: + print(item) + print('---') + for item in lista: + print(item) + print('---')