Emulating Built-ins8:01 with Kenneth Love
What if we want our classes to act like a list or a dict?
One nice thing about emulating built-ins is that you can have your cake and eat it, too. You can make a class that's iterable but not searchable, or vice versa. This gives you a lot of control over how your classes are used.
yield lets you send data back out of a function without ending the execution of the function. Here's an example:
def get_numbers(): numbers = [4, 8, 15, 16, 23, 42] for number in numbers: yield number
If we used this function, with something like
numbers = get_numbers(), we'd have a generator object. This is a special kind of object that has a value, a pointer to the current index, and a
__next__ method (ooh, special method!) that knows how to get the next item from the iterable. We can do
next(numbers) and we'd get 4, then 8, then 15, and so on.
Since we're just returning values from an iterable, we can use
yield from to skip the entire
def get_numbers(): numbers = [4, 8, 15, 16, 23, 42] yield from numbers
If you want to read more about
yield from, here are some docs.
You need to sign up for Treehouse in order to download course files.Sign up