Telegram Group & Telegram Channel
Что выведет этот код?

Iterable - это объект по которому можно пройтись. Для питона это любой объект у которого есть метод __iter__ или __getitem__.

Чтобы преобразовать какой то объект в list, нужно проитерироваться по объекту, т.е. вызвать iter(iterable).
Первым делом смотриться метод __iter__, если он возвращает iterator, то переберая все элементы итератора строиться list.
Но если у объекта нет метода __iter__, но есть метод __getitem__, то создается iterator на основе этого метода.
В метод __getitem__ по очередно передаются индексы (просто числа) от 0 до момента пока __getitem__ не выбросит ошибку StopIteration или IndexError.

Для чего это нужно?
На самом деле это очень старый механизм и в реальности почти не нужный. Так называемая "legacy feature".
Но может быть полезен, когда у вас есть какой то объект и вы хотите как то проитерироваться по нему.


class Library:
def __init__(self, books: list):
self.books = books

def __getitem__(self, index):
return self.books[index]

for book in Library(["a", "b", "c"]):
print(book)


#iter #getitem



tg-me.com/pythrone/14
Create:
Last Update:

Что выведет этот код?

Iterable - это объект по которому можно пройтись. Для питона это любой объект у которого есть метод __iter__ или __getitem__.

Чтобы преобразовать какой то объект в list, нужно проитерироваться по объекту, т.е. вызвать iter(iterable).
Первым делом смотриться метод __iter__, если он возвращает iterator, то переберая все элементы итератора строиться list.
Но если у объекта нет метода __iter__, но есть метод __getitem__, то создается iterator на основе этого метода.
В метод __getitem__ по очередно передаются индексы (просто числа) от 0 до момента пока __getitem__ не выбросит ошибку StopIteration или IndexError.

Для чего это нужно?
На самом деле это очень старый механизм и в реальности почти не нужный. Так называемая "legacy feature".
Но может быть полезен, когда у вас есть какой то объект и вы хотите как то проитерироваться по нему.


class Library:
def __init__(self, books: list):
self.books = books

def __getitem__(self, index):
return self.books[index]

for book in Library(["a", "b", "c"]):
print(book)


#iter #getitem

BY PyThrone




Share with your friend now:
tg-me.com/pythrone/14

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

The Singapore stock market has alternated between positive and negative finishes through the last five trading days since the end of the two-day winning streak in which it had added more than a dozen points or 0.4 percent. The Straits Times Index now sits just above the 3,060-point plateau and it's likely to see a narrow trading range on Monday.

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

telegram from in


Telegram PyThrone
FROM USA