Tài liệu Learning python 4th edition

  • Số trang: 1213 |
  • Loại file: PDF |
  • Lượt xem: 270 |
  • Lượt tải: 0
minhminh

Đã đăng 411 tài liệu

Mô tả:

www.it-ebooks.info Learning Python www.it-ebooks.info www.it-ebooks.info FOURTH EDITION Learning Python Mark Lutz Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo www.it-ebooks.info Learning Python, Fourth Edition by Mark Lutz Copyright © 2009 Mark Lutz. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Julie Steele Production Editor: Sumita Mukherji Copyeditor: Rachel Head Production Services: Newgen North America Indexer: John Bickelhaupt Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: March 1999: December 2003: October 2007: September 2009: First Edition. Second Edition. Third Edition. Fourth Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Learning Python, the image of a wood rat, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-0-596-15806-4 [M] 1252944666 www.it-ebooks.info To Vera. You are my life. www.it-ebooks.info www.it-ebooks.info Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi Part I. Getting Started 1. A Python Q&A Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Why Do People Use Python? Software Quality Developer Productivity Is Python a “Scripting Language”? OK, but What’s the Downside? Who Uses Python Today? What Can I Do with Python? Systems Programming GUIs Internet Scripting Component Integration Database Programming Rapid Prototyping Numeric and Scientific Programming Gaming, Images, Serial Ports, XML, Robots, and More How Is Python Supported? What Are Python’s Technical Strengths? It’s Object-Oriented It’s Free It’s Portable It’s Powerful It’s Mixable It’s Easy to Use It’s Easy to Learn It’s Named After Monty Python How Does Python Stack Up to Language X? 3 4 5 5 7 7 9 9 9 10 10 11 11 11 12 12 13 13 13 14 15 16 16 17 17 17 vii www.it-ebooks.info Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 18 19 19 2. How Python Runs Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Introducing the Python Interpreter Program Execution The Programmer’s View Python’s View Execution Model Variations Python Implementation Alternatives Execution Optimization Tools Frozen Binaries Other Execution Options Future Possibilities? Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 23 24 24 26 29 29 30 32 33 33 34 34 34 3. How You Run Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 The Interactive Prompt Running Code Interactively Why the Interactive Prompt? Using the Interactive Prompt System Command Lines and Files A First Script Running Files with Command Lines Using Command Lines and Files Unix Executable Scripts (#!) Clicking File Icons Clicking Icons on Windows The input Trick Other Icon-Click Limitations Module Imports and Reloads The Grander Module Story: Attributes import and reload Usage Notes Using exec to Run Module Files The IDLE User Interface IDLE Basics Using IDLE Advanced IDLE Tools Other IDEs Other Launch Options viii | Table of Contents 35 37 38 39 41 42 43 44 46 47 47 49 50 51 53 56 57 58 58 60 62 63 64 www.it-ebooks.info Embedding Calls Frozen Binary Executables Text Editor Launch Options Still Other Launch Options Future Possibilities? Which Option Should I Use? Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part I Exercises 64 65 65 66 66 66 68 68 69 70 Part II. Types and Operations 4. Introducing Python Object Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Why Use Built-in Types? Python’s Core Data Types Numbers Strings Sequence Operations Immutability Type-Specific Methods Getting Help Other Ways to Code Strings Pattern Matching Lists Sequence Operations Type-Specific Operations Bounds Checking Nesting Comprehensions Dictionaries Mapping Operations Nesting Revisited Sorting Keys: for Loops Iteration and Optimization Missing Keys: if Tests Tuples Why Tuples? Files Other File-Like Tools Other Core Types How to Break Your Code’s Flexibility 76 77 78 80 80 82 82 84 85 85 86 86 87 87 88 88 90 90 91 93 94 95 96 97 97 99 99 100 Table of Contents | ix www.it-ebooks.info User-Defined Classes And Everything Else Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 101 102 103 103 104 5. Numeric Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Numeric Type Basics Numeric Literals Built-in Numeric Tools Python Expression Operators Numbers in Action Variables and Basic Expressions Numeric Display Formats Comparisons: Normal and Chained Division: Classic, Floor, and True Integer Precision Complex Numbers Hexadecimal, Octal, and Binary Notation Bitwise Operations Other Built-in Numeric Tools Other Numeric Types Decimal Type Fraction Type Sets Booleans Numeric Extensions Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 105 106 108 108 113 113 115 116 117 121 122 122 124 125 127 127 129 133 139 140 141 141 141 6. The Dynamic Typing Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 The Case of the Missing Declaration Statements Variables, Objects, and References Types Live with Objects, Not Variables Objects Are Garbage-Collected Shared References Shared References and In-Place Changes Shared References and Equality Dynamic Typing Is Everywhere Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers x | Table of Contents 143 144 145 146 148 149 151 152 153 153 154 www.it-ebooks.info 7. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 String Literals Single- and Double-Quoted Strings Are the Same Escape Sequences Represent Special Bytes Raw Strings Suppress Escapes Triple Quotes Code Multiline Block Strings Strings in Action Basic Operations Indexing and Slicing String Conversion Tools Changing Strings String Methods String Method Examples: Changing Strings String Method Examples: Parsing Text Other Common String Methods in Action The Original string Module (Gone in 3.0) String Formatting Expressions Advanced String Formatting Expressions Dictionary-Based String Formatting Expressions String Formatting Method Calls The Basics Adding Keys, Attributes, and Offsets Adding Specific Formatting Comparison to the % Formatting Expression Why the New Format Method? General Type Categories Types Share Operation Sets by Categories Mutable Types Can Be Changed In-Place Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 157 158 158 161 162 163 164 165 169 171 172 174 176 177 178 179 181 182 183 184 184 185 187 190 193 194 194 195 195 196 8. Lists and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Lists Lists in Action Basic List Operations List Iteration and Comprehensions Indexing, Slicing, and Matrixes Changing Lists In-Place Dictionaries Dictionaries in Action Basic Dictionary Operations Changing Dictionaries In-Place 197 200 200 200 201 202 207 209 209 210 Table of Contents | xi www.it-ebooks.info More Dictionary Methods A Languages Table Dictionary Usage Notes Other Ways to Make Dictionaries Dictionary Changes in Python 3.0 Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 211 212 213 216 217 223 224 224 9. Tuples, Files, and Everything Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 Tuples Tuples in Action Why Lists and Tuples? Files Opening Files Using Files Files in Action Other File Tools Type Categories Revisited Object Flexibility References Versus Copies Comparisons, Equality, and Truth Python 3.0 Dictionary Comparisons The Meaning of True and False in Python Python’s Type Hierarchies Type Objects Other Types in Python Built-in Type Gotchas Assignment Creates References, Not Copies Repetition Adds One Level Deep Beware of Cyclic Data Structures Immutable Types Can’t Be Changed In-Place Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part II Exercises 225 227 229 229 230 231 232 238 239 241 241 244 246 246 248 249 250 251 251 252 252 253 253 254 254 255 Part III. Statements and Syntax 10. Introducing Python Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 Python Program Structure Revisited Python’s Statements xii | Table of Contents 261 262 www.it-ebooks.info A Tale of Two ifs What Python Adds What Python Removes Why Indentation Syntax? A Few Special Cases A Quick Example: Interactive Loops A Simple Interactive Loop Doing Math on User Inputs Handling Errors by Testing Inputs Handling Errors with try Statements Nesting Code Three Levels Deep Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 264 264 265 266 269 271 271 272 273 274 275 276 276 277 11. Assignments, Expressions, and Prints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Assignment Statements Assignment Statement Forms Sequence Assignments Extended Sequence Unpacking in Python 3.0 Multiple-Target Assignments Augmented Assignments Variable Name Rules Expression Statements Expression Statements and In-Place Changes Print Operations The Python 3.0 print Function The Python 2.6 print Statement Print Stream Redirection Version-Neutral Printing Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 279 280 281 284 288 289 292 295 296 297 298 300 302 306 308 308 308 12. if Tests and Syntax Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 if Statements General Format Basic Examples Multiway Branching Python Syntax Rules Block Delimiters: Indentation Rules Statement Delimiters: Lines and Continuations A Few Special Cases 311 311 312 312 314 315 317 318 Table of Contents | xiii www.it-ebooks.info Truth Tests The if/else Ternary Expression Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 320 321 324 324 324 13. while and for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 while Loops General Format Examples break, continue, pass, and the Loop else General Loop Format pass continue break Loop else for Loops General Format Examples Loop Coding Techniques Counter Loops: while and range Nonexhaustive Traversals: range and Slices Changing Lists: range Parallel Traversals: zip and map Generating Both Offsets and Items: enumerate Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 327 328 328 329 329 330 331 331 332 334 334 335 341 342 343 344 345 348 349 349 350 14. Iterations and Comprehensions, Part 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 Iterators: A First Look The Iteration Protocol: File Iterators Manual Iteration: iter and next Other Built-in Type Iterators List Comprehensions: A First Look List Comprehension Basics Using List Comprehensions on Files Extended List Comprehension Syntax Other Iteration Contexts New Iterables in Python 3.0 The range Iterator The map, zip, and filter Iterators Multiple Versus Single Iterators xiv | Table of Contents 351 352 354 356 358 359 359 361 362 366 367 368 369 www.it-ebooks.info Dictionary View Iterators Other Iterator Topics Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 370 372 372 372 373 15. The Documentation Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 Python Documentation Sources # Comments The dir Function Docstrings: __doc__ PyDoc: The help Function PyDoc: HTML Reports The Standard Manual Set Web Resources Published Books Common Coding Gotchas Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part III Exercises 375 376 376 377 380 383 386 387 387 387 389 389 390 390 Part IV. Functions 16. Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395 Why Use Functions? Coding Functions def Statements def Executes at Runtime A First Example: Definitions and Calls Definition Calls Polymorphism in Python A Second Example: Intersecting Sequences Definition Calls Polymorphism Revisited Local Variables Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 396 396 398 399 400 400 400 401 402 402 403 403 404 404 405 405 Table of Contents | xv www.it-ebooks.info 17. Scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 Python Scope Basics Scope Rules Name Resolution: The LEGB Rule Scope Example The Built-in Scope The global Statement Minimize Global Variables Minimize Cross-File Changes Other Ways to Access Globals Scopes and Nested Functions Nested Scope Details Nested Scope Examples The nonlocal Statement nonlocal Basics nonlocal in Action Why nonlocal? Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 407 408 410 411 412 414 415 416 418 419 419 419 425 425 426 429 432 433 434 18. Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 Argument-Passing Basics Arguments and Shared References Avoiding Mutable Argument Changes Simulating Output Parameters Special Argument-Matching Modes The Basics Matching Syntax The Gritty Details Keyword and Default Examples Arbitrary Arguments Examples Python 3.0 Keyword-Only Arguments The min Wakeup Call! Full Credit Bonus Points The Punch Line... Generalized Set Functions Emulating the Python 3.0 print Function Using Keyword-Only Arguments Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers xvi | Table of Contents 435 436 438 439 440 441 442 443 444 446 450 453 454 455 456 456 457 459 460 461 462 www.it-ebooks.info 19. Advanced Function Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 Function Design Concepts Recursive Functions Summation with Recursion Coding Alternatives Loop Statements Versus Recursion Handling Arbitrary Structures Function Objects: Attributes and Annotations Indirect Function Calls Function Introspection Function Attributes Function Annotations in 3.0 Anonymous Functions: lambda lambda Basics Why Use lambda? How (Not) to Obfuscate Your Python Code Nested lambdas and Scopes Mapping Functions over Sequences: map Functional Programming Tools: filter and reduce Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 463 465 465 466 467 468 469 469 470 471 472 474 474 475 477 478 479 481 483 483 483 20. Iterations and Comprehensions, Part 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 List Comprehensions Revisited: Functional Tools List Comprehensions Versus map Adding Tests and Nested Loops: filter List Comprehensions and Matrixes Comprehending List Comprehensions Iterators Revisited: Generators Generator Functions: yield Versus return Generator Expressions: Iterators Meet Comprehensions Generator Functions Versus Generator Expressions Generators Are Single-Iterator Objects Emulating zip and map with Iteration Tools Value Generation in Built-in Types and Classes 3.0 Comprehension Syntax Summary Comprehending Set and Dictionary Comprehensions Extended Comprehension Syntax for Sets and Dictionaries Timing Iteration Alternatives Timing Module Timing Script Timing Results 485 486 487 489 490 492 492 497 498 499 500 506 507 507 508 509 509 510 511 Table of Contents | xvii www.it-ebooks.info Timing Module Alternatives Other Suggestions Function Gotchas Local Names Are Detected Statically Defaults and Mutable Objects Functions Without returns Enclosing Scope Loop Variables Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part IV Exercises 513 517 518 518 520 522 522 522 523 523 524 Part V. Modules 21. Modules: The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529 Why Use Modules? Python Program Architecture How to Structure a Program Imports and Attributes Standard Library Modules How Imports Work 1. Find It 2. Compile It (Maybe) 3. Run It The Module Search Path Configuring the Search Path Search Path Variations The sys.path List Module File Selection Advanced Module Selection Concepts Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 529 530 531 531 533 533 534 534 535 535 537 538 538 539 540 541 541 542 22. Module Coding Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543 Module Creation Module Usage The import Statement The from Statement The from * Statement Imports Happen Only Once import and from Are Assignments xviii | Table of Contents 543 544 544 545 545 546 546 www.it-ebooks.info Cross-File Name Changes import and from Equivalence Potential Pitfalls of the from Statement Module Namespaces Files Generate Namespaces Attribute Name Qualification Imports Versus Scopes Namespace Nesting Reloading Modules reload Basics reload Example Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 547 548 548 550 550 552 552 553 554 555 556 558 558 558 23. Module Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561 Package Import Basics Packages and Search Path Settings Package __init__.py Files Package Import Example from Versus import with Packages Why Use Package Imports? A Tale of Three Systems Package Relative Imports Changes in Python 3.0 Relative Import Basics Why Relative Imports? The Scope of Relative Imports Module Lookup Rules Summary Relative Imports in Action Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 561 562 563 564 566 566 567 569 570 570 572 574 575 575 581 582 582 24. Advanced Module Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583 Data Hiding in Modules Minimizing from * Damage: _X and __all__ Enabling Future Language Features Mixed Usage Modes: __name__ and __main__ Unit Tests with __name__ Using Command-Line Arguments with __name__ Changing the Module Search Path The as Extension for import and from 583 584 584 585 586 587 590 591 Table of Contents | xix
- Xem thêm -