Giving a Hand6:07 with Kenneth Love
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
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.
You need to sign up for Treehouse in order to download course files.Sign up