Chapter Nine Working withCreating Modules 2 Fm httpxkcdcom353 Creating Modules Create use and even share your own modules Reuse code Could reuse the Card Hand and Deck ID: 569692
Download Presentation The PPT/PDF document "Guide to Programming with Python" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Guide to Programming with Python
Chapter
Nine
Working with/Creating ModulesSlide2
2
Fm: http://xkcd.com/353/Slide3
Creating Modules
Create, use, and even share your own modules
Reuse code
Could reuse the
Card, Hand, and
Deck
classes for different card games
Manage large projectsProfessional projects can be hundreds of thousands of lines longWould be nearly impossible to maintain in one file
3Slide4
Using
Modules
Module
imported using filename, just like built-in
modules Import programmer-created module the same way you import a built-in module
import random
random.randrange(10)
from random import *
randrange(10)
(import * operation may not work very well on Windows platforms, where the
filesystem does not always have accurate information about the case of a filename!)
4
What else have you tried?Slide5
Writing
Modules
Write module as a collection of related programming components, like functions and classes,
in a single file
File is just Python file with extension .
py
(
games module is file
games.py
)
class Player(object):
""" A player for a game. """ def __
init__(self, name, score = 0): self.name
= name self.score = score
def __
str__(sefl
): return "name=" + name + " score=" + str(score)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
5Slide6
if __name ==
"
__main__
"
class
Player(object
):
""" A player for a game. """ def __init__(self
, name, score = 0):
...
if __name__ == "__main__": test =
Player("Tom
", 100) print tet
raw_input("\n\nPress the enter key to exit.")Why do I need to do this? To make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file (__name__ == "__main__"
is true )
6Slide7
Using Imported Functions and Classes
num =
games.ask_number(question
= "How many?",
low = 2, high = 5
)
player
= games.Player(name, score)
Use imported programmer-created modules the same way as you use imported built-in modules
7Slide8
What’s are Defined in a Module?
The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:
import sys
dir(sys)Slide9
Module Not Found?The Module Search Path
When a module named spam is imported, the interpreter searches for a file named
spam.py
in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH.
Modules are searched in the list of directories given by the variable sys.path import sys
sys.path.append('/home/yye/lib/python
')Slide10
Packages
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a
submodule
named B in a package named A.
sound/ Top-level package __init__.py
Initialize the sound package
formats/
Subpackage for file format conversions
__
init__.py
wavread.py wavwrite.py ... effects/ Subpackage
for sound effects __init__.py
echo.pyimport sound.effects.echo #or
from sound.effects import echoSlide11
The Blackjack Game -
Pseudocode
Deal each player and dealer initial two cards
For each player
While the player asks for a hit and the player is not busted
Deal the player an additional card
If there are no players still playing
Show the dealer’s two cards
Otherwise
While the dealer must hit and the dealer is not busted
Deal the dealer an additional card
If the dealer is busted
For each player who is still playing The player winsOtherwise For each player who is still playing If the player’s total is greater than the dealer’s total
The player wins Otherwise, if the player’s total is less than the dealer’s total The player loses Otherwise The player pushes
11Slide12
The Blackjack Game – Class Hierarchy
Figure 9.8: Blackjack classes
Inheritance hierarchy of classes for the Blackjack game
12Slide13
The Blackjack Game - Classes
Table 9.1: Blackjack classes
Guide to Programming with Python
13Slide14
Summary
You can write, import, and even share your own modules
You
write a module as a collection of related programming components, like functions and classes, in a single Python file
Programmer-created modules can be imported the same way that built-in modules are, with an
import
statement
You test to see if
__name__
is equal to
"__main__" to make a module identify itself as such
14Slide15
Key OOP Concepts
Inheritance
Inheriting vs. overriding (Implementing a new one or adding)
Polymorphism means that the same message can be sent to objects of different classes
related by inheritance and achieve different and appropriate results. For example, when Human or Comput object calls flip_or_take
() methods, they do things differently. Polymorphism enables objects of different types to be substituted (e.g., the human-
vs
-compute Flip game to human-vs-human Flip game). EncapsulationThe inclusion within a program object of all the resources needed for the object to function: the methods and the data to hide the details of the inner workings from the client code.
Encapsulation is a principle of abstraction -- a concept or idea not associated with any specific instance (OOP attempts to abstract both data and code)