Knowing all this, we can create an iterator that returns one item from a sequence, one by one, by getting `items[0]`, `items[1]`, ... until it runs out.
✨Here's how:
The previous example is big, but simple in essence:
- The iterator starts with a list of items and an index of 0
- On every __next__() call, it returns the next number in the list
- Once it runs out, it raises StopIteration
✨That's the internals of iteration.
e.g. a Reversed:
Now note that:
- An iterable needs to return an iterator in `__iter__`
- An iterator needs to define a `__next__`
So if you make a class that defines both, and make `__iter__(self)` just returns `self`, it'll work the same way.
✨So objects can be both iterable and an iterator:
• • •
Missing some Tweet in this thread? You can try to
force a refresh
Compared to the last two, this one is much simpler!
`mro` stands for "Method Resolution Order", and exists on all classes:
The `__mro__` is a tuple of classes, and it always starts with the class itself.
What it actually represents, is the order in which it tries to find a method call.
Hence the name 🤷♂️
It's better with an example, let's understand how methods are stored:
By using `vars()`, which turns an object into a dictionary, we can see that a class' methods are stored on the class itself.
✨Makes sense so far? Not for long, now let's look at the `bool` class: