Creating Modules


You first learned about modules in Chapter 3, in the section "Using the import Statement," where you met the random module. But a powerful aspect of Python programming is that you can create, use, and even share your own modules. Creating your own modules provides important benefits.

First, by creating your own modules, you can reuse code, which can save you time and effort. For example, you could reuse the Card, Hand, and Deck classes you've seen so far to create many different types of card games without having to reinvent basic card, deck, and hand functionality every time.

Second, by breaking up a program into logical modules, large programs become easier to manage. So far, the programs you've been working with have been contained in one file. Since they've been pretty short, this is no big deal. But imagine a program that's thousands (or even tens of thousands) of lines long. Working with a program of this size, in one, massive file, would be a real nightmare (professional projects, by the way, can easily get this large).

Third, by creating modules, you can share your genius. If you create a useful module, you can e-mail it to a friend, who then can use it much like any built-in Python module.

Introducing the Simple Game Program

The Simple Game program, as the name suggests, is simple. The program first asks how many players wish to participate and then proceeds to get each player's name. Finally, the program assigns a random score to each player and displays the results. Not very thrilling, but the point of the program is not the game, but rather how the game works. The program uses a brand-new module with functions and a class that I created. Figure 9.7 displays the results of the program.

click to expand
Figure 9.7: Several functions and a class used in the program are from a programmer-created module.

Writing Modules

Normally, I'd show you the code for the next program, Simple Game, but in this section, I go over the module I've written that Simple Game uses.

You create a module the same way you write any other Python program. When you create a module, though, you should build a collection of related programming components, such as functions and classes, and store them in a single file to be imported into a new program.

I created a basic module, called games, that contains two functions and a class that might be useful in creating a game. Here's the code:

 # Games # Demonstrates module creation # Michael Dawson 4/10/03 class Player(object):     """ A player for a game. """     def __init__(self, name, score = 0):         self.name = name         self.score = score     def __str__(self):         rep = self.name + ":\t" + str(self.score)         return rep def ask_yes_no(question):     """ Ask a yes or no question."""     response = None     while response not in ("y", "n"):         response = raw_input(question).lower()     return response def ask_number(question, low, high):     """ Ask for a number within a range."""     response = None     while response not in range(low, high):         response = int(raw_input(question))     return response if __name__ == "__main__":     print "You ran this module directly (and did not 'import' it)."     raw_input("\n\nPress the enter key to exit.") 

This module is named games because I saved the file with the name games.py. Programmer-created modules are named (and imported) based on their file names.

The bulk of the module is straightforward. The Player class defines an object with two attributes, name and score, which are set in the constructor method. There's only one other method, __str__(), which returns a string representation so that objects can be printed.

You've seen the next two functions, ask_yes_no() and ask_number(), before in Chapter 6, in the "The ask_yes_no() Function" and the "The ask_number() Function" sections.

The next part of the program introduces a new idea, related to modules. The condition of the if statement, __name__ == "__main__", is true if the program is run directly. It's false if the file is imported as a module. So, if the games.py file is run directly, a message is displayed telling the user that the file is meant to be imported and not directly run.

Importing Modules

Now that you've seen the games module, I'll introduce the code of the Simple Game program. The following are the first few lines:

 # Simple Game # Demonstrates importing modules # Michael Dawson 4/10/03 import games, random 

You import a programmer-created module the same way you import a built-in module, with the import statement. In fact, I import the games module along with the familiar random module in the same import statement.

TRAP

If a programmer-created module isn't in the same directory as the program that imports it, Python won't be able to find the module. There are ways around this. It's even possible to install a programmer-created module so that it's available system-wide, just like built-in modules, but this requires a special installation procedure that's beyond the scope of this book. So for now, make sure that any module you want to import is in the same directory as the programs that import it.

Using Imported Functions and Classes

I use the imported modules in the remainder of the Simple Game program. After welcoming the players and setting up a simple loop, I ask how many players there will be in the game:

 print "Welcome to the world's simplest game!\n" again = None while again != "n":     players = []     num = games.ask_number(question = "How many players? (2 - 5): ",                             low = 2, high = 5) 

I get the number of players by calling the ask_number() function from the games module. Just as with other imported modules, to call a function, I use dot notation, specifying first the module name, followed by the function name.

Next, for each player, I get the player's name and generate a random score between 1 and 100 by calling the randrange() function from the random module. Then, I create a player object using this name and score. Since the Player class is defined in the games module, again I use dot notation and include the module name before the class name. Then, I append this new player object to a list of players.

     for i in range(num):         name = raw_input("Player name: ")         score = random.randrange(100) + 1         player = games.Player(name, score)         players.append(player) 

Next, I print each player in the game:

     print "\nHere are the game results:"     for player in players:         print player 

Finally, I ask if the players want to play another game. I use the ask_yes_no() function from the games module to obtain my answer:

     again = games.ask_yes_no("\nDo you want to play again? (y/n): ") raw_input("\n\nPress the enter key to exit.") 




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net