Class Iterators : Python Basics

preview_player
Показать описание
How to iterate over custom classes in Python:
- Iterator method
- Generator method
Рекомендации по теме
Комментарии
Автор

generator based solution seems problematic (if not a wrong one) as it doesn't fulfill the iter/next protocol. isn't it?
because there is no __next__ dunder, you must run and exhaust all members otherwise you don't have any way to return to the abundant loop

class Cafe:

def __init__(self, menu):
self._menu = menu

def __iter__(self):
print('kuku')
for item in self._menu:
yield item

def func(self):
print('kuku')

c = Cafe(['Cafe-A', 'Cafe-B', 'Cafe-C'])

a = iter(c)
c.func()
?? now what?? # there is no __next__

ShukyPersky
Автор

Thanks for your detailed explanation! your video is truly helpful.
I was stuck in understanding how 'for in' works in the background, and finally found the answer here.
By the way, how can I find the mechanics of similar operations, like 'while in' and 'if in', I can't find them in official doc.

hayek
Автор

Got most of the session. Last demo on separate iterator class i.e. instead of return self in __iter__(), the use of return is kinda confusing. Thanks for the tutorial post.

gopsda
Автор

HI, ur explaining the actual happening in python, could you guide me, how did u learn this way, what is the process or resource you followed ?, could you share those things, so that I would like to learn the way you are teaching so basic and simple of all the concepts. Thank you

munivoltarc