Classes & Iterators - Dive Into Python 3 - 0 views
-
Comprehensions are just a simple form of iterators. Generators are just a simple form of iterators
-
The first argument of every class method, including the __init__() method, is always a reference to the current instance of the class. By convention, this argument is named self.
- ...6 more annotations...
-
in most cases), __iter__() simply returns self, since this class implements its own __next__() method.
-
the __next__() method raises a StopIteration exception, this signals to the caller that the iteration is exhausted. Unlike most exceptions, this is not an error; it’s a normal condition that just means that the iterator has no more values to generate. If the caller is a for loop, it will notice this StopIteration exception and gracefully exit the loop. (In other words, it will swallow the exception.)
-
Do not use yield here; that’s a bit of syntactic sugar that only applies when you’re using generators. Here you’re creating your own iterator from scratch; use return instead