Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
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
Briefly, 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 for
loop:
def get_numbers():
numbers = [4, 8, 15, 16, 23, 42]
yield from numbers
If you want to read more about yield
and yield from
, here are some docs.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up