Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
- Controlling Conversion 6:24
- Dream Car 1 objective
- Math 6:22
- Multiplication 2 objectives
- Emulating Built-ins 8:01
- Iterable Album 1 objective
- Subclassing Built-ins 10:28
- Double 3 objectives
- Frustration 1 objective
- Constructicons 5:26
- Dream Vacation 1 objective
- Special Methods 7:30
- Proper Properties 2 objectives

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
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 up-
JASON LEE
17,352 Points1 Answer
-
Cameron Ganley
4,049 Points3 Answers
-
Gene Higgins
16,582 Points1 Answer
-
Adrian Diaz
3,500 Points3 Answers
-
E. T.
Python Development Techdegree Student 884 Points1 Answer
-
E. T.
Python Development Techdegree Student 884 Points3 Answers
-
Adem Gun
1,511 PointsI'm having trouble grasping most of what's going on, should I keep going?
Posted by Adem GunAdem Gun
1,511 Points1 Answer
-
PLUS
Benyamin Kohanchi
Courses Plus Student 2,342 Points1 Answer
-
PLUS
Benyamin Kohanchi
Courses Plus Student 2,342 Points1 Answer
-
Elena Chen
1,503 Pointsself.slots
Posted by Elena ChenElena Chen
1,503 Points1 Answer
-
Patrick Brusven
14,520 Points1 Answer
-
Timothy Tseng
3,292 Points1 Answer
-
Antoni Majewski
3,128 Points2 Answers
-
Sohail Mirza
Python Web Development Techdegree Student 5,158 Points1 Answer
-
daniel steinberg
14,651 Points1 Answer
-
Andrew Bickham
1,461 Points3 Answers
View all discussions for this video
Related 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