Guide to Programming with Python Chapter Nine Working with/Creating Modules.

15
Guide to Programming with Python Chapter Nine Working with/Creating Modules

Transcript of Guide to Programming with Python Chapter Nine Working with/Creating Modules.

Page 1: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

Guide to Programming with Python

Chapter NineWorking with/Creating Modules

Page 2: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

2

Fm: http://xkcd.com/353/

Page 3: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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 projects– Professional projects can be hundreds of thousands

of lines long– Would be nearly impossible to maintain in one file

3

Page 4: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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 randomrandom.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?

Page 5: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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

5

Page 6: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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 )

6

Page 7: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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

7

Page 8: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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 sysdir(sys)

Page 9: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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')

Page 10: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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.py

import sound.effects.echo #orfrom sound.effects import echo

Page 11: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

The Blackjack Game - PseudocodeDeal each player and dealer initial two cardsFor each player While the player asks for a hit and the player is not busted Deal the player an additional cardIf there are no players still playing Show the dealer’s two cardsOtherwise 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 wins

Otherwise

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 pushes11

Page 12: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

The Blackjack Game – Class Hierarchy

Figure 9.8: Blackjack classesInheritance hierarchy of classes for the Blackjack game

12

Page 13: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

The Blackjack Game - Classes

Table 9.1: Blackjack classes

Guide to Programming with Python 13

Page 14: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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

14

Page 15: Guide to Programming with Python Chapter Nine Working with/Creating Modules.

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).

Encapsulation– The 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)