Tài liệu Learning python 3rd edition

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

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

Mô tả:

Learning Python Other resources from O’Reilly Related titles oreilly.com Programming Python Python Cookbook™ Python in a Nutshell Python Pocket Reference Twisted Network Programming Essentials oreilly.com is more than a complete catalog of O’Reilly books. You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples. oreillynet.com is the essential portal for developers interested in open and emerging technologies, including new platforms, programming languages, and operating systems. Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in documenting the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit conferences.oreilly.com for our upcoming events. Safari Bookshelf (safari.oreilly.com) is the premier online reference library for programmers and IT professionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or simply flip to the page you need. Try it today for free. THIRD EDITION Learning Python Mark Lutz Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo Learning Python, Third Edition by Mark Lutz Copyright © 2008 O’Reilly Media, Inc. 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 (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Tatiana Apandi Production Editor: Sumita Mukherji Copyeditor: Rachel Head Proofreader: Sumita Mukherji Indexer: Julie Hawks Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: March 1999: First Edition. December 2003: Second Edition. October 2007: Third 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. Java™ is a trademark of Sun Microsystems, Inc. .NET is a registered trademark of Microsoft Corporation. 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. This book uses RepKover™, a durable and flexible lay-flat binding. ISBN-10: 0-596-51398-4 ISBN-13: 978-0-596-51398-6 [M] To Vera. You are my life. Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxix 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, AI, XML, Robots, and More What Are Python’s Technical Strengths? It’s Object Oriented It’s Free It’s Portable It’s Powerful It’s Mixable 3 5 5 6 7 8 9 9 9 10 10 11 11 11 12 12 12 13 13 14 15 vii It’s Easy to Use It’s Easy to Learn It’s Named After Monty Python How Does Python Stack Up to Language X? Chapter Summary Brain Builder Chapter Quiz Quiz Answers 15 17 17 18 19 20 20 20 2. How Python Runs Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Introducing the Python Interpreter Program Execution The Programmer’s View Python’s View Byte code compilation The Python Virtual Machine (PVM) Performance implications Development implications Execution Model Variations Python Implementation Alternatives CPython Jython IronPython Execution Optimization Tools The Psyco just-in-time compiler The Shedskin C++ translator Frozen Binaries Future Possibilities? Chapter Summary Brain Builder Chapter Quiz Quiz Answers viii | Table of Contents 22 24 24 25 25 26 26 27 27 28 28 28 29 29 29 30 31 32 32 33 33 33 3. How You Run Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 Interactive Coding Using the Interactive Prompt System Command Lines and Files Using Command Lines and Files Unix Executable Scripts (#!) Clicking File Icons Clicking Icons on Windows The raw_input Trick Other Icon-Click Limitations Module Imports and Reloads The Grander Module Story: Attributes Modules and namespaces import and reload Usage Notes The IDLE User Interface IDLE Basics Using IDLE Advanced IDLE Tools Other IDEs Embedding Calls Frozen Binary Executables Text Editor Launch Options Other Launch Options Future Possibilities? Which Option Should I Use? Chapter Summary Brain Builder Chapter Quiz Quiz Answers Brain Builder: Part I Exercises 34 37 37 40 41 42 42 44 45 45 47 49 49 50 51 52 54 54 56 56 57 57 57 58 58 59 59 59 61 Table of Contents | ix Part II. Types and Operations 4. Introducing Python Object Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 x | 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 List Comprehensions Dictionaries Mapping Operations Nesting Revisited Sorting Keys: for Loops Iteration and Optimization Missing Keys: if Tests 66 67 68 69 70 71 72 73 74 75 75 76 76 77 77 78 79 79 80 81 83 84 Tuples Why Tuples? Files Other File-Like Tools Other Core Types How to Break Your Code’s Flexibility User-Defined Classes And Everything Else Chapter Summary Brain Builder Chapter Quiz Quiz Answers 85 85 85 86 87 88 88 89 90 91 91 91 Table of Contents 5. Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Python Numeric Types Numeric Literals Built-in Numeric Tools and Extensions Python Expression Operators Mixed Operators Follow Operator Precedence Parentheses Group Subexpressions Mixed Types Are Converted Up Preview: Operator Overloading Numbers in Action Variables and Basic Expressions Numeric Display Formats Division: Classic, Floor, and True Bitwise Operations Long Integers Complex Numbers Hexadecimal and Octal Notation Other Built-in Numeric Tools Other Numeric Types Decimal Numbers Sets Booleans Third-Party Extensions Chapter Summary Brain Builder Chapter Quiz Quiz Answers 93 94 95 96 97 97 97 98 99 99 100 102 103 103 104 105 106 107 107 108 109 110 110 111 111 111 6. The Dynamic Typing Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 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 112 112 114 115 116 118 119 121 Table of Contents | xi Chapter Summary Brain Builder Chapter Quiz Quiz Answers 121 122 122 122 7. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 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 Unicode Strings Encode Larger Character Sets Strings in Action Basic Operations Indexing and Slicing Extended slicing: the third limit String Conversion Tools Character code conversions Changing Strings String Formatting Advanced String Formatting Dictionary-Based String Formatting String Methods String Method Examples: Changing Strings String Method Examples: Parsing Text Other Common String Methods in Action The Original string Module General Type Categories Types Share Operation Sets by Categories Mutable Types Can Be Changed In-Place Chapter Summary Brain Builder Chapter Quiz Quiz Answers xii | Table of Contents 124 125 125 127 129 130 132 132 133 135 136 138 139 140 141 142 143 144 146 147 148 149 149 150 150 151 151 151 8. Lists and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 Lists Lists in Action Basic List Operations Indexing, Slicing, and Matrixes Changing Lists In-Place Index and slice assignments List method calls Other common list operations Dictionaries Dictionaries in Action Basic Dictionary Operations Changing Dictionaries In-Place More Dictionary Methods A Languages Table Dictionary Usage Notes Using dictionaries to simulate flexible lists Using dictionaries for sparse data structures Avoiding missing-key errors Using dictionaries as “records” Other ways to make dictionaries Chapter Summary Brain Builder Chapter Quiz Quiz Answers 152 154 154 155 156 156 157 159 160 161 162 163 163 165 166 166 167 167 168 169 170 171 171 171 9. Tuples, Files, and Everything Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 Tuples Tuples in Action Tuple syntax peculiarities: commas and parentheses Conversions and immutability Why Lists and Tuples? Files Opening Files Using Files 172 173 174 174 175 176 176 177 Table of Contents | xiii Files in Action Storing and parsing Python objects in files Storing native Python objects with pickle Storing and parsing packed binary data in files Other File Tools Type Categories Revisited Object Flexibility References Versus Copies Comparisons, Equality, and Truth The Meaning of True and False in Python Python’s Type Hierarchies 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 Brain Builder Chapter Quiz Quiz Answers Brain Builder: Part II Exercises 178 178 180 181 182 182 183 184 186 188 189 191 191 191 192 193 193 193 195 195 195 196 Part III. Statements and Syntax 10. Introducing Python Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 Python Program Structure Revisited Python’s Statements A Tale of Two ifs What Python Adds What Python Removes Parentheses are optional End of line is end of statement End of indentation is end of block Why Indentation Syntax? A Few Special Cases xiv | Table of Contents 201 202 203 204 204 204 204 205 206 208 Statement rule special cases Block rule special case 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 Brain Builder Chapter Quiz Quiz Answers 208 209 210 210 211 212 213 214 215 216 216 216 11. Assignment, Expressions, and print . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Assignment Statements Assignment Statement Forms Sequence Assignments Advanced sequence assignment patterns Multiple-Target Assignments Multiple-target assignment and shared references Augmented Assignments Augmented assignment and shared references Variable Name Rules Naming conventions Names have no type, but objects do Expression Statements Expression Statements and In-Place Changes print Statements The Python “Hello World” Program Redirecting the Output Stream The print >> file Extension Chapter Summary Brain Builder Chapter Quiz Quiz Answers 217 218 219 220 222 222 223 225 225 227 227 228 229 229 230 231 232 234 235 235 235 Table of Contents | xv 12. if Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 if Statements General Format Basic Examples Multiway Branching Python Syntax Rules Block Delimiters Statement Delimiters A Few Special Cases Truth Tests The if/else Ternary Expression Chapter Summary Brain Builder Chapter Quiz Quiz Answers 236 236 237 237 239 240 241 242 243 244 246 247 247 247 13. while and for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 while Loops General Format Examples break, continue, pass, and the Loop else General Loop Format Examples pass continue break else More on the loop else clause for Loops General Format Examples Basic usage Other data types Tuple assignment in for Nested for loops xvi | Table of Contents 248 249 249 250 250 251 251 251 252 252 253 254 254 256 256 256 257 257 Iterators: A First Look File Iterators Other Built-in Type Iterators Other Iteration Contexts User-Defined Iterators Loop Coding Techniques Counter Loops: while and range Nonexhaustive Traversals: range Changing Lists: range Parallel Traversals: zip and map Dictionary construction with zip Generating Both Offsets and Items: enumerate List Comprehensions: A First Look List Comprehension Basics Using List Comprehensions on Files Extended List Comprehension Syntax Chapter Summary Brain Builder Chapter Quiz Quiz Answers 258 260 262 263 264 265 265 266 267 268 270 271 272 272 273 274 275 276 276 276 14. The Documentation Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 Python Documentation Sources # Comments The dir Function Docstrings: _ _doc_ _ User-defined docstrings Docstring standards Built-in docstrings PyDoc: The help Function PyDoc: HTML Reports Standard Manual Set Web Resources Published Books Common Coding Gotchas 278 279 279 280 281 282 282 283 285 289 289 290 291 Table of Contents | xvii Chapter Summary Brain Builder Chapter Quiz Quiz Answers Brain Builder: Part III Exercises 293 294 294 294 295 Part IV. Functions 15. Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 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 Brain Builder Chapter Quiz Quiz Answers 300 300 302 303 303 304 304 305 306 306 306 307 308 308 309 309 309 16. Scopes and Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310 Scope Rules Python Scope Basics 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 xviii | Table of Contents 310 311 312 314 314 316 317 318 319 Scopes and Nested Functions Nested Scope Details Nested Scope Examples Factory functions Retaining enclosing scopes’ state with defaults Nested scopes and lambdas Scopes versus defaults with loop variables Arbitrary scope nesting Passing Arguments Arguments and Shared References Avoiding Mutable Argument Changes Simulating Output Parameters Special Argument-Matching Modes Keyword and Default Examples Keywords Defaults Arbitrary Arguments Examples Collecting arguments Unpacking arguments Combining Keywords and Defaults The min Wakeup Call Full credit Bonus points The punch line A More Useful Example: General Set Functions Argument Matching: The Gritty Details Chapter Summary Brain Builder Chapter Quiz Quiz Answers 320 320 321 321 323 324 324 326 326 327 329 329 330 332 332 333 333 334 334 335 336 336 337 338 338 339 340 342 342 343 17. Advanced Function Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 Anonymous Functions: lambda lambda Expressions Why Use lambda? How (Not) to Obfuscate Your Python Code Nested lambdas and Scopes 344 344 346 347 348 Table of Contents | xix
- Xem thêm -