Contents

About the Author

About the Technical Reviewer

Preface

Introduction

CHAPTER 1 Instant Hacking: The Basics

Installing Python

Windows

Linux and UNIX

Macintosh

Other Distributions

Keeping in Touch and Up-to-Date

The Interactive Interpreter

Algo . . . What?

Numbers and Expressions

Large Integers

Hexadecimals and Octals

Variables

Statements

Getting Input from the User

Functions

Modules

cmath and Complex Numbers

Back to the __future__

Saving and Executing Your Programs

Running Your Python Scripts from a Command Prompt

Making Your Scripts Behave Like Normal Programs

Comments

Strings

Single-Quoted Strings and Escaping Quotes

Concatenating Strings

String Representations, str and repr

input vs. raw_input

Long Strings, Raw Strings, and Unicode

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 2 Lists and Tuples

Sequence Overview

Common Sequence Operations

Indexing

Slicing

Adding Sequences

Multiplication

Membership

Length, Minimum, and Maximum

Lists: Python’s Workhorse

The list Function

Basic List Operations

List Methods

Tuples: Immutable Sequences

The tuple Function

Basic Tuple Operations

So What’s the Point?

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 3 Working with Strings

Basic String Operations

String Formatting: The Short Version

String Formatting: The Long Version

Simple Conversion

Width and Precision

Signs, Alignment, and Zero-Padding

String Methods

find

join

lower

replace

split

strip

translate

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 4 Dictionaries: When Indices Won’t Do

Dictionary Uses

Creating and Using Dictionaries

The dict Function

Basic Dictionary Operations

String Formatting with Dictionaries

Dictionary Methods

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 5 Conditionals, Loops, and Some Other Statements

More About print and import

Printing with Commas

Importing Something As Something Else

Assignment Magic

Sequence Unpacking

Chained Assignments

Augmented Assignments

Blocks: The Joy of Indentation

Conditions and Conditional Statements

So That’s What Those Boolean Values Are For

Conditional Execution and the if Statement

else Clauses

elif Clauses

Nesting Blocks

More Complex Conditions

Assertions

Loops

while Loops

for Loops

Iterating Over Dictionaries

Some Iteration Utilities

Breaking Out of Loops

else Clauses in Loops

List Comprehension—Slightly Loopy

And Three for the Road

Nothing Happened!

Deleting with del

Executing and Evaluating Strings with exec and eval

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 6 Abstraction

Laziness Is a Virtue

Abstraction and Structure

Creating Your Own Functions

Documenting Functions

Functions That Aren’t Really Functions

The Magic of Parameters

Where Do the Values Come From?

Can I Change a Parameter?

Keyword Parameters and Defaults

Collecting Parameters

Reversing the Process

Parameter Practice

Scoping

Recursion

Two Classics: Factorial and Power

Another Classic: Binary Search

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 7 More Abstraction

The Magic of Objects

Polymorphism

Encapsulation

Inheritance

Classes and Types

What Is a Class, Exactly?

Making Your Own Classes

Attributes, Functions, and Methods

Privacy Revisited

The Class Namespace

Specifying a Superclass

Investigating Inheritance

Multiple Superclasses

Interfaces and Introspection

Some Thoughts on Object-Oriented Design

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 8 Exceptions

What Is an Exception?

Making Things Go Wrong . . . Your Way

The raise Statement

Custom Exception Classes

Catching Exceptions

Look, Ma, No Arguments!

More Than One except Clause

Catching Two Exceptions with One Block

Catching the Object

A Real Catchall

When All Is Well

And Finally

Exceptions and Functions

The Zen of Exceptions

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 9 Magic Methods, Properties, and Iterators

Before We Begin

Constructors

Overriding Methods in General, and the Constructor in Particular

Calling the Unbound Superclass Constructor

Using the super Function

Item Access

The Basic Sequence and Mapping Protocol

Subclassing list, dict, and str

More Magic

Properties

The property Function

Static Methods and Class Methods

__getattr__, __setattr__, and Friends

Iterators

The Iterator Protocol

Making Sequences from Iterators

Generators

Making a Generator

A Recursive Generator

Generators in General

Generator Methods

Simulating Generators

The Eight Queens

Generators and Backtracking

The Problem

State Representation

Finding Conflicts

The Base Case

The Recursive Case

Wrapping It Up

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 10 Batteries Included

Modules

Modules Are Programs

Modules Are Used to Define Things

Making Your Modules Available

Packages

Exploring Modules

What’s in a Module?

Getting Help with help

Documentation

Use the Source

The Standard Library: A Few Favorites

sys

os

fileinput

Sets, Heaps, and Deques

time

random

shelve

re

Other Interesting Standard Modules

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 11 Files and Stuff

Opening Files

File Modes

Buffering

The Basic File Methods

Reading and Writing

Piping Output

Reading and Writing Lines

Closing Files

Using the Basic File Methods

Iterating over File Contents

Doing It Byte by Byte

One Line at a Time

Reading Everything

Lazy Line Iteration with fileinput

File Iterators

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 12 Graphical User Interfaces

A Plethora of Platforms

Downloading and Installing wxPython

Building a Sample GUI Application

Getting Started

Windows and Components

Labels, Titles, and Positions

More Intelligent Layout

Event Handling

The Finished Program

But I’d Rather Use

Using Tkinter

Using Jython and Swing

Using Something Else

A Quick Summary

What Now?

CHAPTER 13 Database Support

The Python Database API

Global Variables

Exceptions

Connections and Cursors

Types

SQLite and PySQLite

Getting Started

A Sample Database Application

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 14 Network Programming

A Handful of Networking Modules

The socket Module

The urllib and urllib2 Modules

Other Modules

SocketServer and Friends

Multiple Connections

Forking and Threading with SocketServer

Asynchronous I/O with select and poll

Twisted

Downloading and Installing Twisted

Writing a Twisted Server

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 15 Python and the Web

Screen Scraping

Tidy and XHTML Parsing

Beautiful Soup

Dynamic Web Pages with CGI

Step 1. Preparing the Web Server

Step 2. Adding the Pound Bang Line

Step 3. Setting the File Permissions

CGI Security Risks

A Simple CGI Script

Debugging with cgitb

Using the cgi Module

A Simple Form

One Step Up: mod_python

Installing mod_python

CGI Handler

PSP

The Publisher

Web Application Frameworks

Web Services: Scraping Done Right

RSS and Friends

Remote Procedure Calls with XML-RPC

SOAP

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 16 Testing, 1-2-3

Test First, Code Later

Precise Requirement Specification

Planning for Change

The 1-2-3 (and 4) of Testing

Tools for Testing

doctest

unittest

Beyond Unit Tests

Source Code Checking with PyChecker and PyLint

Profiling

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 17 Extending Python

The Best of Both Worlds

The Really Easy Way: Jython and IronPython

Writing C Extensions

A Swig of . . . SWIG

Hacking It on Your Own

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 18 Packaging Your Programs

Distutils Basics

Wrapping Things Up

Building an Archive File

Creating a Windows Installer or an RPM Package

Compiling Extensions

Creating Executable Programs with py2exe

A Quick Summary

New Functions in This Chapter

What Now?

CHAPTER 19 Playful Programming

Why Playful?

The Jujitsu of Programming

Prototyping

Configuration

Extracting Constants

Configuration Files

Logging

If You Can’t Be Bothered

If You Want to Learn More

A Quick Summary

What Now?

CHAPTER 20 Project 1: Instant Markup

What’s the Problem?

Useful Tools

Preparations

First Implementation

Finding Blocks of Text

Adding Some Markup

Second Implementation

Handlers

A Handler Superclass

Rules

A Rule Superclass

Filters

The Parser

Constructing the Rules and Filters

Putting It All Together

Further Exploration

What Now?

CHAPTER 21 Project 2: Painting a Pretty Picture

What’s the Problem?

Useful Tools

Preparations

First Implementation

Drawing with ReportLab

Constructing Some PolyLines

Writing the Prototype

Second Implementation

Getting the Data

Using the LinePlot Class

Further Exploration

What Now?

CHAPTER 22 Project 3: XML for All Occasions

What’s the Problem?

Useful Tools

Preparations

First Implementation

Creating a Simple Content Handler

Creating HTML Pages

Second Implementation

A Dispatcher Mix-In Class

Factoring Out the Header, Footer, and Default Handling

Support for Directories

The Event Handlers

Further Exploration

What Now?

CHAPTER 23 Project 4: In the News

What’s the Problem?

Useful Tools

Preparations

First Implementation

Second Implementation

Further Exploration

What Now?

CHAPTER 24 Project 5: A Virtual Tea Party

What’s the Problem?

Useful Tools

Preparations

First Implementation

The ChatServer Class

The ChatSession Class

Putting It Together

Second Implementation

Basic Command Interpretation

Rooms

Login and Logout Rooms

The Main Chat Room

The New Server

Further Exploration

What Now?

CHAPTER 25 Project 6: Remote Editing with CGI

What’s the Problem?

Useful Tools

Preparations

First Implementation

Second Implementation

Creating the File Name Form

Writing the Editor Script

Writing the Save Script

Running the Editor

Further Exploration

What Now?

CHAPTER 26 Project 7: Your Own Bulletin Board

What’s the Problem?

Useful Tools

Preparations

First Implementation

Second Implementation

Writing the Main Script

Writing the View Script

Writing the Edit Script

Writing the Save Script

Trying It Out

Further Exploration

What Now?

CHAPTER 27 Project 8: File Sharing with XML-RPC

What’s the Problem?

Useful Tools

Preparations

First Implementation

Implementing a Simple Node

Trying Out the First Implementation

Second Implementation

Creating the Client Interface

Raising Exceptions

Validating File Names

Trying Out the Second Implementation

Further Exploration

What Now?

CHAPTER 28 Project 9: File Sharing II—Now with GUI!

What’s the Problem?

Useful Tools

Preparations

First Implementation

Second Implementation

Further Exploration

What Now?

CHAPTER 29 Project 10: Do-It-Yourself Arcade Game

What’s the Problem?

Useful Tools

pygame

pygame.locals

pygame.display

pygame.font

pygame.sprite

pygame.mouse

pygame.event

pygame.image

Preparations

First Implementation

Second Implementation

Further Exploration

What Now?

APPENDIX A The Short Version

The Basics

Functions

Objects and Stuff

Some Loose Ends

APPENDIX B Python Reference

Expressions

Statements

Simple Statements

Compound Statements

APPENDIX C Online Resources

Python Distributions

Python Documentation

Useful Toolkits and Modules

Newsgroups, Mailing Lists, and Blogs

APPENDIX D Python 3.0

Strings and I/O

Strings, Bytes, and Encodings

Console I/O

New String Formatting

Classes and Functions

Function Annotation

Abstract Base Classes

Class Decorators and New Metaclass Syntax

Keyword-Only Parameters

Nonlocal Variables

Iterables, Comprehensions, and Views

Extended Iterable Unpacking

Dictionary and Set Comprehension

Dictionary Views

Iterator Return Values

Things That Have Gone

Some Minor Issues

The Standard Library

Other Stuff

INDEX

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset