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
Now that we can roll dice and compare them, it's time to start on the Yatzy game play.
Are you confused by how we're using the die_class
argument? Functions and classes are first-class citizens in Python which means we can pass them around and use them as values just like we would any other variable. That means we can point a variable or parameter at a class or function and then call that variable just like we would the original class. Here's another example:
class Car:
pass
class Van:
pass
class Motorcycle:
pass
def vehicle_factory(cls, count):
for _ in range(count):
yield cls()
Now we could make any number of Car
, Van
, or Motorcycle
instances that we want (and, notice, it's a generator function since we're using yield
; if our vehicle manufacturing required a lot of memory, we could still be polite to other processes and not tie up all of the RAM with our factory). We'd do this with code similar to
cars = vehicle_factory(Car, 50)
vans = vehicle_factory(Van, 10)
motorcycles = vehicle_factory(Motorcycle, 100)
Each time the for
loop executes, it finds the class that was passed in and creates an instance of it. This ability of Python makes for really flexible code.
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