1、Wrox Programmer to ProgrammerJoin the discussion Using Python 2.6 and Python 3.1BeginningPythonJames Payne Get more out of Programmer to ProgrammerInteractTake an active role online by participating in our P2P forums Wrox Online LibraryHundreds of our books are available online through BWrox Blox Do
2、wnload short informational pieces and code to keep you up to date and out of trouble!Join the CommunitySign up for our free monthly newsletter at BrowseReady for more Wrox? We have books and e-books available on .NET, SQL Server, Java, XML, Visual Basic, C#/ C+, and much more!Contact Us. We always l
3、ike to get feedback from our readers. Have a book idea? Need community support? Let us know by e-mailing wrox- Beginning Python: Using Python 2.6 and Python 3.1Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxviiPart I: Dipping Your Toe into
4、 PythonChapter 1: Programming Basics and Strings . . . . . . . . . . . . . . . . . . . . . . . . . . 3Chapter 2: Numbers and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Chapter 3: Variables Names for Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 31Part II
5、: Python Language and the Standard LibraryChapter 4: Making Decisions . 51Chapter 5: Functions . 71Chapter 6: Classes and Objects . 93Chapter 7: Organizing Programs . 111Chapter 8: Files and Directories . 127Chapter 9: Other Features of the Language . 143Chapter 10: Building a Module . 157Chapter 11
6、: Text Processing . 189Part III: Putting Python to WorkChapter 12: Testing . 207Chapter 13: Writing a GUI with Python . 227Chapter 14: Accessing Databases. 239Chapter 15: Using Python for XML . 265Chapter 16: Network Programming . 287Continues Chapter 17: Extension Programming with C . 337Chapter 18
7、: Numerical Programming . 367Chapter 19: An Introduction to Django . 387Chapter 20: Web Applications and Web Services . 407Chapter 21: Integrating Java with Python . 481Part IV: AppendicesAppendix A: Answers to the Exercises . 515Appendix B: Online Resources. 549Appendix C: Whats New in Python 3.1 .
8、 553Appendix D: Glossary . 559Index . 569 Beginning Python BeginningPythonUsing Python 2.6 and Python 3.1James PayneWiley Publishing, Inc. Beginning Python: Using Python 2.6 and Python 3.1 Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN Copyright 2010 by Wiley Publishing
9、, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 978-0-470-41463-7Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photoc
10、opying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosew
11、ood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http:/ of Liability/Disclaimer
12、of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created
13、or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is
14、required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising here from. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does no
15、t mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is rea
16、d.For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.Wiley also publishes its books in a variety of electronic formats. Some content that
17、appears in print may not be available in electronic books.Library of Congress Control Number: 2009936814Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affilia
18、tes, in the United States and other countries, and may not be used without written permission. Python is a registered trademark of Python Software Foundation. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mention
19、ed in this book. To my patient and loving wife, Whitney, who believed in me before I did. And to my parents, Ronnie and Sharon Payne, who raised me to believe I could do anything I put my mind to, even when I told them I wanted to be Santa Claus. For my brother, Ron, who read my work even when it wa
20、s bad, Dorjan, Eric, Clem, and Nick because they know things about me and will tell them if I dont include them. About the AuthorJames Payne (Margate, FL) is Editor-in-Chief of Developer Shed, Inc. and has been writing and programming since the age of seven years old. Proficient in many languages, h
21、e has written over 400 articles covering practically every major programming language. As a contractor, he develops proprietary software for the financial industry using Python and likes to dabble in Django in his spare time. CreditsExecutive EditorCarol LongProject EditorEd ConnorTechnical EditorCh
22、ris McAvoyProduction EditorsAmy Weintraub and Tim TateCopy EditorKim CoferEditorial DirectorRobyn B. SieskyEditorial ManagerMary Beth Wakefield Marketing ManagerDavid MayhewProduction ManagerTim TateVice President and Executive Group PublisherRichard SwadleyVice President and Executive PublisherBarr
23、y PruettAssociate PublisherJim MinatelProject Coordinator, CoverLynsey StanfordProofreadersScott Klemp and Kristy Eldredge, Word OneIndexerRon StraussCover Image AcknowledgmentsI would like to acknowledge the gang at Developer Shed: Jack and Jay Kim, whose constant hatred is an inspiration, Charles
24、Fagundes, who made me an editor and not just a writer, Keith Lee, who provided coding support, and a special thanks to Jenny Ruggieri, who got me the job that got me this book. Lastly, Id like to thank all of the people that worked on the previous editions of this book for laying the groundwork, and
25、 the Editors Carol Long, Jenny Watson, Ed Connor, and Chris McAvoy who helped me meet deadlines no matter how much I didnt want to.I would also like to acknowledge Guido Von Rossum, without whom there would be no language to write about. ContentsIntroduction xxviiPart I: Dipping Your Toe into Python
26、 1Chapter 1: Programming Basics and Strings 3How Programming is Different from Using a Computer 3Programming is Consistency 4Programming is Control 4Programming Copes with Change 5What All That Means Together 5The First Steps 5Installing Python 3.1 on Non-Windows Systems 6Using the Python Shell 6Beg
27、inning to Use Python Strings 7What is a String? 7Why the Quotes? 7Why Three Types of Quotes? 8Using the print() Function 8Understanding Different Quotes 9Putting Two Strings Together 11Joining Strings with the Print() Function 12Putting Strings Together in Different Ways 12Summary 13Exercises 14Chap
28、ter 2: Numbers and Operators 15Different Kinds of Numbers 15Numbers in Python 16Program Files 18Using the Different Types 19Basic Math 21Some Surprises 23Using Numbers 24Order of Evaluation 24Number Formats 25 ContentsxviMistakes Will Happen 26Some Unusual Cases 27Summary 28Exercises 29Chapter 3: Va
29、riables Names for Values 31Referring to Data Using Names for Data 31Changing Data Through Names 33Copying Data 33Names You Cant Use and Some Rules 34Using More Built-in Types 34Tuples Unchanging Sequences of Data 34Lists Changeable Sequences of Data 37Dictionaries Groupings of Data Indexed by Name 3
30、9Treating a String Like a List 41Special Types 42Other Common Sequence Properties 43Referencing the Last Elements 43Ranges of Sequences 44Growing Lists by Appending Sequences 45Using Lists to Temporarily Store Data 45Working with Sets 46Summary 47Exercises 48Part II: Python Language and the Standard
31、 Library 49Chapter 4: Making Decisions 51Comparing Values Are They the Same? 51Doing the Opposite Not Equal 53Comparing Values Which One Is More? 54More Than or Equal, Less Than or Equal 55Reversing True and False 56Looking for the Results of More Than One Comparison 56How to Get Decisions Made 57Re
32、petition 60How to Do Something Again and Again 60Stopping the Repetition 62Handling Errors 65Trying Things Out 65 ContentsxviiSummary 67Exercises 69Chapter 5: Functions 71Putting Your Program into Its Own File 71Functions: Grouping Code under a Name 73Choosing a Name 75Describing a Function in the F
33、unction 75The Same Name in Two Different Places 76Making Notes to Yourself 78Asking a Function to Use a Value You Provide 79Checking Your Parameters 81Setting a Default Value for a ParameterJust in Case 83Calling Functions from within Other Functions 84Functions Inside of Functions 86Flagging an Err
34、or on Your Own Terms 87Layers of Functions 88How to Read Deeper Errors 88Summary 89Exercises 90Chapter 6: Classes and Objects 93Thinking About Programming 93What is an Object? 93Objects You Already Know 94Looking Ahead: How You Want to Use Objects 95Defining a Class 96How Code Can Be Made into an Ob
35、ject 96Objects and Their Scope 104Summary 107Exercises 108Chapter 7: Organizing Programs 111Modules 112Importing a Module So That You Can Use It 112Making a Module from Pre-existing Code 113Using Modules Starting with the Command Line 115Changing How Import Works Bringing in More 118Packages 118 Con
36、tentsxviiiModules and Packages 120Bringing Everything into the Current Scope 120Re-importing Modules and Packages 121Basics of Testing Your Modules and Packages 124Summary 124Exercises 125Chapter 8: Files and Directories 127File Objects 127Writing Text Files 128Appending Text to a File 129Reading Te
37、xt Files 130File Exceptions 131Paths and Directories 131Exceptions in os 132Paths 132Directory Contents 135Obtaining Information about Files 136Renaming, Moving, Copying, and Removing Files 137Example: Rotating Files 138Creating and Removing Directories 140Globbing 140Summary 142Exercises 142Chapter
38、 9: Other Features of the Language 143Lambda and Filter: Short Anonymous Functions 143Map: Short-Circuiting Loops 144Decisions within Lists List Comprehension 145Generating Iterators for Loops 146Special String Substitution Using Dictionaries 148Featured Modules 149Getopt Getting Options from the Co
39、mmand Line 149Using More Than One Process 152Threads Doing Many Things in the Same Process 154Summary 156Exercises 156 ContentsxixChapter 10: Building a Module 157Exploring Modules 157Importing Modules 159Finding Modules 159Digging through Modules 160Creating Modules and Packages 162Working with Cla
40、sses 163Defining Object-Oriented Programming 163Creating Classes 163Extending Existing Classes 165Finishing Your Modules 166Defining Module-Specific Errors 166Choosing What to Export 167Documenting Your Modules 168Testing Your Module 176Running a Module as a Program 178Creating a Whole Module 179Ins
41、talling Your Modules 183Summary 187Exercises 188Chapter 11: Text Processing 189Why Text Processing Is So Useful 189Searching for Files 190Clipping Logs 191Sifting through Mail 192Navigating the File System with the os Module 192Working with Regular Expressions and the re Module 199Summary 203Exercis
42、es 204Part III: Putting Python to Work 205Chapter 12: Testing 207Assertions 208Test Cases and Test Suites 209Test Fixtures 213Putting It All Together with Extreme Programming 216 ContentsxxImplementing a Search Utility in Python 216A More Powerful Python Search 222Formal Testing in the Software Life
43、 Cycle 224Summary 225Chapter 13: Writing a GUI with Python 227GUI Programming Toolkits for Python 228Tkinter Introduction 229Creating GUI Widgets with Tkinter 229Resizing the Widget 230Configuring Widget Options 231Putting the Widgets to Work 231Creating Layouts 232Packing Order 233Controlling Widge
44、t Appearances 233Radio Buttons and Checkboxes 235Dialog Boxes 236Other Widget Types 237Summary 238Exercises 238Chapter 14: Accessing Databases 239Working with DBM Persistent Dictionaries 240Choosing a DBM Module 240Creating Persistent Dictionaries 241Accessing Persistent Dictionaries 243Deciding Whe
45、n to Use DBM and When to Use a Relational Database 245Working with Relational Databases 245Writing SQL Statements 247Defining Tables 249Setting Up a Database 250Using the Python Database APIs 252Downloading Modules 252Creating Connections 253Working with Cursors 253Working with Transactions and Comm
46、itting the Results 260Examining Module Capabilities and Metadata 261Handling Errors 261Summary 262Exercises 263 ContentsxxiChapter 15: Using Python for XML 265What Is XML? 265A Hierarchical Markup Language 265A Family of Standards 267What Is a Schema/DTD? 268What Are Document Models For? 268Do You N
47、eed One? 268Document Type Definitions 268An Example DTD 268DTDs Arent Exactly XML 270Limitations of DTDs 270Schemas 270An Example Schema 270Schemas Are Pure XML 271Schemas Are Hierarchical 271Other Advantages of Schemas 271XPath 272HTML as a Subset of XML 272The HTML DTDs 273HTMLParser 273XML Librar
48、ies Available for Python 274What Is SAX? 274Stream-based 275Event-driven 275What Is DOM? 275In-memory Access 275Why Use SAX or DOM 275Capability Trade-Offs 276Memory Considerations 276Speed Considerations 276SAX and DOM Parsers Available for Python 276xml.sax 276xml.dom.minidom 277Intro to XSLT 280X
49、SLT Is XML 280Transformation and Formatting Language 280Functional, Template-Driven 280What Is lxml? 280Element Classes 281Adding Text to Elements 282 ContentsxxiiParsing with lxml 283Parsing Files 284Summary 285Exercises 285Chapter 16: Network Programming 287Understanding Protocols 289Comparing Protocols and Programming Languages 289The Internet Protocol Stack 290A Little Bit About the Internet Protocol 292Sending Internet E-mail 293The E-mail File Format 294MIME Messages 295Sending Mail with SMTP and smtplib 303Retrieving Internet E-mail 305Parsing a Local Mail Spool with mailbox 305Fetchi