Đăng ký Đăng nhập

Tài liệu Beginning python

.PDF
679
424
74

Mô tả:

TEAM LinG Beginning Python TEAM LinG TEAM LinG Beginning Python Peter Norton, Alex Samuel, David Aitel, Eric Foster-Johnson, Leonard Richardson, Jason Diamond, Aleatha Parker, Michael Roberts TEAM LinG Beginning Python Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN-10: 0-7645-9654-3 ISBN-13: 978-0-7645-9654-4 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/SQ/QX/QV/IN Library of Congress Cataloging-in-Publication Data: Beginning Python / Peter Norton. p. cm. Includes bibliographical references and index. ISBN-13: 978-0-7645-9654-4 (paper/website) ISBN-10: 0-7645-9654-3 (paper/website) 1. Python (Computer program language) I. Norton, Peter, 1974QA76.73.P98B45 2005 005.13’3--dc22 2005013968 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, 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 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions. LIMIT OF LIABILITY/DISCLAIMER 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 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 REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN THEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. TEAM LinG About the Authors Peter Norton (NY, NY) has been working with Unix and Linux for over a decade at companies large and small solving problems with Linux. An officer of the NY Linux Users Group, he can be found on the nylug-talk mailing list. Peter coauthored Professional RHEL3. He works for a very large financial company in NYC, plying his Python and open-source skills. Alex Samuel (San Diego, CA) has developed software for biology researchers and now studies highenergy physics at Caltech. Alex has worked on many GNU/Linux development tools, including GCC, and co-founded CodeSourcery LLC, a consulting firm specializing in GNU/Linux development tools. David Aitel (NY, NY) is the CEO of Immunity and a coauthor of Shellcoder’s Handbook. Eric Foster-Johnson (Minneapolis, MN) uses Python extensively with Java, and is a veteran author, most recently completing Beginning Shell Scripting. Leonard Richardson (San Francisco, CA) writes useful Python packages with silly names. Jason Diamond (CA) Jason Diamond is a software development instructor for DevelopMentor and a consultant specializing in C++, .NET, Python, and XML. He spends most of his spare time contributing to open-source projects using his favorite language, Python. Aleathea Parker (San Francisco CA) is a programmer working as a publication engineer for a major software company, coding primarily in Python and XSLT. She has a background in web applications and content management. Michael Roberts (Puerto Rico) has been programming professionally in C, Perl, and Python for long enough that Python didn’t actually exist when he started. He is the chief perpetrator of the wftk open-source workflow toolkit, and he swears that it will someday be finished, for certain values of “finished”. TEAM LinG TEAM LinG Credits Acquisitions Editor Graphics and Production Specialists Debra Williams Cauley Sean Decker Carrie Foster Lauren Goddard Denny Hager Jennifer Heleine Amanda Spagnuolo Development Editor Kelly D. Henthorne Production Editor William A. Barton Quality Control Technicians Copy Editor Luann Rouff Leann Harney Joe Niesen Carl William Pierce Production Manager Tim Tate Media Development Specialists Editorial Manager Mary Beth Wakefield Angela Denny Kit Malone Travis Silvers Vice President & Executive Group Publisher Proofreading and Indexing Richard Swadley TECHBOOKS Production Services Vice President and Publisher Joseph B. Wikert Project Coordinator Kristie Rees TEAM LinG TEAM LinG To my Claudia, for keeping me thinking straight through a crazy time. To my mom, Eunice, for bringing me food and asking if I was okay throughout. To Debra, for roping me into this. And to all of the authors, I want to thank you for making it to the finish line. Whoa! I didn’t know what I was getting you all into! —P. N. To my dad, Clarence A. Johnson, 1922–2005. —E. F-J. For my mother. —L. R. For Jilly: 1 = 2. —J. D. To Aaron, for putting up with me. —A. P. To my wife, Agnes, in revenge for her doctoral thesis. —M. R. TEAM LinG TEAM LinG Contents Acknowledgments Introduction xxix xxxi Chapter 1: Programming Basics and Strings 1 How Programming Is Different from Using a Computer 1 Programming Is Consistency Programming Is Control Programming Copes with Change What All That Means Together 2 2 2 3 The First Steps 3 Starting codeEditor Using codeEditor’s Python Shell 3 4 Try It Out: Starting the Python Shell 4 Beginning to Use Python — Strings 5 What Is a String? Why the Quotes? 5 6 Try It Out: Entering Strings with Different Quotes 6 Understanding Different Quotes 6 Putting Two Strings Together 8 Try It Out: Using + to Combine Strings 8 Putting Strings Together in Different Ways 9 Try It Out: Using a Format Specifier to Populate a String Try It Out: More String Formatting Displaying Strings with Print Try It Out: Printing Text with Print Summary Exercises Chapter 2: Numbers and Operators Different Kinds of Numbers Numbers in Python Try It Out: Using Type with Different Numbers Try It Out: Creating an Imaginary Number 9 9 10 10 10 11 13 13 14 14 15 TEAM LinG Contents Program Files Try It Out: Using the Shell with the Editor Using the Different Types Try It Out Including Different Numbers in Strings Try It Out: Escaping the % Sign in Strings Basic Math Try It Out Doing Basic Math Try It Out: Using the Modulus Operation Some Surprises Try It Out: Printing the Results Using Numbers Order of Evaluation Try It Out: Using Math Operations Number Formats Try It Out: Using Number Formats Mistakes Will Happen Try It Out: Making Mistakes Some Unusual Cases Try It Out: Formatting Numbers as Octal and Hexadecimal Summary Exercises 15 16 17 18 18 19 19 20 20 21 21 21 21 22 22 23 23 24 24 24 25 Chapter 3: Variables — Names for Values 27 Referring to Data – Using Names for Data 27 Try It Out: Assigning Values to Names Changing Data Through Names Try It Out: Altering Named Values Copying Data Names You Can’t Use and Some Rules Using More Built-in Types Tuples — Unchanging Sequences of Data Try It Out: Creating and Using a Tuple Try It Out: Accessing a Tuple Through Another Tuple Lists — Changeable Sequences of Data Try It Out Viewing the Elements of a List 29 29 29 30 30 30 31 33 33 Dictionaries — Groupings of Data Indexed by Name 34 Try It Out: Making a Dictionary Try It Out: Getting the Keys from a Dictionary 34 35 Treating a String Like a List Special Types xii 28 28 36 38 TEAM LinG Contents Other Common Sequence Properties Referencing the Last Elements Ranges of Sequences Try It Out: Slicing Sequences Growing Lists by Appending Sequences Using Lists to Temporarily Store Data Try It Out: Popping Elements from a List Summary Exercises Chapter 4: Making Decisions Comparing Values — Are They the Same? Try It Out: Comparing Values for Sameness Doing the Opposite — Not Equal 38 38 39 39 40 40 40 41 42 43 43 43 45 Try It Out: Comparing Values for Difference 45 Comparing Values — Which One Is More? 45 Try It Out: Comparing Greater Than and Less Than More Than or Equal, Less Than or Equal Reversing True and False Try It Out: Reversing the Outcome of a Test Looking for the Results of More Than One Comparison How to Get Decisions Made Try It Out: Placing Tests within Tests Repetition How to Do Something — Again and Again Try It Out: Using a while Loop Stopping the Repetition Try It Out: Using else While Repeating Try It Out: Using continue to Keep Repeating Handling Errors Trying Things Out Try It Out: Creating an Exception with Its Explanation Summary Exercises Chapter 5: Functions Putting Your Program into Its Own File Try It Out: Run a Program with Python -i 45 47 47 47 48 48 49 51 51 51 52 54 54 55 55 56 57 58 59 59 61 xiii TEAM LinG Contents Functions: Grouping Code under a Name 61 Try It Out: Defining a Function 61 Choosing a Name Describing a Function in the Function 62 63 Try It Out: Displaying __doc__ 63 The Same Name in Two Different Places Making Notes to Yourself Try It Out: Experimenting with Comments Asking a Function to Use a Value You Provide Try It Out Invoking a Function with Parameters Checking Your Parameters Try It Out: Determining More Types with the type Function Try It Out: Using Strings to Compare Types Setting a Default Value for a Parameter — Just in Case 64 65 65 66 67 68 69 69 70 Try It Out: Setting a Default Parameter 70 Calling Functions from within Other Functions 71 Try It Out: Invoking the Completed Function 72 Functions Inside of Functions Flagging an Error on Your Own Terms Layers of Functions How to Read Deeper Errors Summary Exercises 72 73 74 74 75 76 Chapter 6: Classes and Objects 79 Thinking About Programming 79 Objects You Already Know Looking Ahead: How You Want to Use Objects Defining a Class How Code Can Be Made into an Object Try It Out: Defining a Class Try It Out: Creating an Object from Your Class Try It Out: Writing an Internal Method Try It Out: Writing Interface Methods Try It Out: Using More Methods Objects and Their Scope Try It Out: Creating Another Class Summary Exercises xiv 79 81 81 81 82 82 84 85 87 89 89 92 93 TEAM LinG Contents Chapter 7: Organizing Programs Modules Importing a Module So That You Can Use It Making a Module from Pre-existing Code Try It Out: Creating a Module Try It Out: Exploring Your New Module Using Modules — Starting With the Command Line Try It Out: Printing sys.argv Changing How Import Works — Bringing in More Packages Try It Out: Making the Files in the Kitchen Class Modules and Packages Bringing Everything into the Current Scope Try It Out: Exporting Modules from a Package Re-importing Modules and Packages Try It Out: Examining sys.modules Basics of Testing Your Modules and Packages Summary Exercises Chapter 8: Files and Directories File Objects Writing Text Files Reading Text Files Try It Out: Printing the Lengths of Lines in the Sample File File Exceptions 95 96 96 97 97 98 99 100 101 101 102 103 103 104 104 105 106 106 107 109 109 110 111 112 113 Paths and Directories 113 Paths Directory Contents 114 116 Try It Out: Getting the Contents of a Directory Try It Out: Listing the Contents of Your Desktop or Home Directory Obtaining Information about Files Recursive Directory Listings Renaming, Moving, Copying, and Removing Files Example: Rotating Files Creating and Removing Directories Globbing 116 118 118 118 119 120 121 122 TEAM LinGxv Contents Pickles Try It Out: Creating a Pickle File Pickling Tips Efficient Pickling Summary Exercises Chapter 9: Other Features of the Language Lambda and Filter: Short Anonymous Functions Reduce Try It Out: Working with Reduce Map: Short-Circuiting Loops Try It Out: Use Map Decisions within Lists — List Comprehension Generating Lists for Loops 123 123 124 125 125 125 127 127 128 128 129 129 130 131 Try It Out: Examining an xrange Object 132 Special String Substitution Using Dictionaries 133 Try It Out: String Formatting with Dictionaries Featured Modules Getopt — Getting Options from the Command Line Using More Than One Process Threads — Doing Many Things in the Same Process Storing Passwords Summary Exercises Chapter 10: Building a Module Exploring Modules Importing Modules Finding Modules Digging through Modules Creating Modules and Packages Try It Out: Creating a Module with Functions Working with Classes Defining Object-Oriented Programming Creating Classes Try It Out: Creating a Meal Class Extending Existing Classes xvi 133 134 134 137 139 140 141 142 143 143 145 145 146 150 150 151 151 151 152 153 TEAM LinG Contents Finishing Your Modules Defining Module-Specific Errors Choosing What to Export Documenting Your Modules Try It Out: Viewing Module Documentation Testing Your Module Running a Module as a Program Try It Out: Running a Module Creating a Whole Module Try It Out: Finishing a Module Try It Out: Smashing Imports Installing Your Modules Try It Out: Creating an Installable Package Summary Exercises Chapter 11: Text Processing Why Text Processing Is So Useful Searching for Files Clipping Logs Sifting through Mail 154 154 155 156 157 162 164 164 165 165 169 170 171 174 174 175 175 176 177 178 Navigating the File System with the os Module 178 Try It Out: Listing Files and Playing with Paths Try It Out: Searching for Files of a Particular Type Try It Out: Refining a Search 180 181 183 Working with Regular Expressions and the re Module 184 Try It Out: Fun with Regular Expressions Try It Out: Adding Tests Summary Exercises Chapter 12: Testing Assertions Try It Out: Using Assert Test Cases and Test Suites Try It Out: Testing Addition Try It Out: Testing Faulty Addition Test Fixtures Try It Out: Working with Test Fixtures 186 187 189 189 191 191 192 193 194 195 196 197 xvii TEAM LinG Contents Putting It All Together with Extreme Programming Implementing a Search Utility in Python Try It Out: Writing a Test Suite First Try It Out: A General-Purpose Search Framework A More Powerful Python Search Try It Out: Extending the Search Framework Formal Testing in the Software Life Cycle Summary 199 200 201 203 205 206 207 208 Chapter 13: Writing a GUI with Python 209 GUI Programming Toolkits for Python PyGTK Introduction pyGTK Resources Creating GUI Widgets with pyGTK 209 210 211 213 Try It Out: Writing a Simple pyGTK Program GUI Signals GUI Helper Threads and the GUI Event Queue Try It Out: Writing a Multithreaded pyGTK App Widget Packing Glade: a GUI Builder for pyGTK GUI Builders for Other GUI Frameworks Using libGlade with Python A Glade Walkthrough Starting Glade Creating a Project Using the Palette to Create a Window Putting Widgets into the Window Glade Creates an XML Representation of the GUI Try It Out: Building a GUI from a Glade File Creating a Real Glade Application Advanced Widgets Further Enhancing PyRAP Summary Exercises Chapter 14: Accessing Databases Working with DBM Persistent Dictionaries Choosing a DBM Module Creating Persistent Dictionaries Try It Out: Creating a Persistent Dictionary xviii 213 214 216 219 222 223 224 225 225 226 227 227 228 230 231 231 238 241 248 248 249 250 250 251 251 TEAM LinG Contents Accessing Persistent Dictionaries Try It Out: Accessing Persistent Dictionaries Deciding When to Use DBM and When to Use a Relational Database Working with Relational Databases Writing SQL Statements Defining Tables Setting Up a Database Try It Out: Creating a Gadfly Database Using the Python Database APIs Downloading Modules Creating Connections Working with Cursors Try It Out: Inserting Records Try It Out: Writing a Simple Query Try It Out: Writing a Complex Join Try It Out: Updating an Employee’s Manager Try It Out: Removing Employees Working with Transactions and Committing the Results Examining Module Capabilities and Metadata Handling Errors Summary Exercises Chapter 15: Using Python for XML What Is XML? A Hierarchical Markup Language A Family of Standards What Is a Schema/DTD? What Are Document Models For? Do You Need One? 252 253 255 255 257 259 260 261 262 263 263 264 264 266 267 269 270 271 272 272 273 274 275 275 275 277 278 278 278 Document Type Definitions 278 An Example DTD DTDs Aren’t Exactly XML Limitations of DTDs 278 280 280 Schemas An Example Schema Schemas Are Pure XML Schemas Are Hierarchical Other Advantages of Schemas Schemas Are Less Widely Supported 280 280 281 281 281 281 TEAM LinGxix
- Xem thêm -

Tài liệu liên quan