Python是流行、开源、面向对象的编程语言,既可以用于编写单机运行的程序也可以编写脚本程序,具有可移植,强大、易用等特点。跟随专业教师学习是最快捷的掌握此语言的方式。新版的《学习Python》把你带到Mark Lutz和David Ascher面前,他们是著名的Python专家和培训师,他们的用语亲切且组织良好的文章已经指导许多编程者精通这种语言。对本书第一版的褒奖: “这本书最好之处在于作者在提供有用的实例与详细解释说明之间取得近乎完美的平衡。无论你是有经验的计算机程序员还是初学者,这本书对于学习Python语言都是非常适合的。” ———Andrew Morrison, CedarLug 《学习Python》(第二版)给程序员提供了一个学习Python和面向对象编程的综合学习工具。它根据1999年该书第一版发布以来语言的大量变化做了更新。本书介绍了最近发布的Python2.3的基本要素并涵盖了新的特性,如列表内涵,嵌套作用域和迭代器/产生器。除了语言特性,《学习Python》(第二版)还为初级程序员提供了新的内容,包括新的面向对象编程回顾,动态类型,新的关于编程起步和配置选项的讨论,新的关于文档的内容等等。全书用新的实例使得语言特性的应用更加具体。《学习Python》(第二版)首先给出了理解和构造Python程序必需的所有信息,包括类型、运算符、表达式、类、函数、模块和异常。然后,作者给出了更高级的内容,通过真实的应用和可用扩展库说明如何用Python完成一般的任务。全书提供了练习以检验自己的新技能。《学习Python》(第二版)是本可灵活选读的图书,它让读者能够集中深入Python语言的核心。随着通读全书,你将获得对Python深入而完整的理解,这将帮助你自己开发大型的应用程序。本书适合于任何不仅仅想停留于了解Python而且想更好的掌握它的人。
le width="100%"> Preface Part I. Getting Started 1. A Python Q&A Session Why Do People Use Python? Is Python a Scripting Language? Okay, But What's the Downside? Who Uses Python Today? What Can I Do with Python? What Are Python's Technical Strengths? How Does Python Stack Up to Language X? 2. How Python Runs Programs Introducing the Python Interpreter Program Execution Execution Model Variations 3. How You Run Programs Interactive Coding System Command Lines and Files Clicking Windows File Icons Module Imports and Reloads The IDLE User Interface Other IDEs Embedding Calls Frozen Binary Executables Text Editor Launch Options Other Launch Options Future Possibilities? Which Option Should I Use? Part I Exercises Part II. Types and Operations 4. Numbers Python Program Structure Why Use Built-in Types? Numbers Python Expression Operators Numbers in Action The Dynamic Typing Interlude 5. Strings String Literals Strings in Action String Formatting String Methods General Type Categories 6. Lists and Dictionaries Lists Lists in Action Dictionaries Dictionaries in Action 7. Tuples, Files, and Everything Else Tuples Files Type Categories Revisited Object Generality References Versus Copies Comparisons, Equality, and Truth Python's Type Hierarchies Other Types in Python Built-in Type Gotchas Part II Exercises Part III. Statements and Syntax 8. Assignment, Expressions, and Print Assignment Statements Expression Statements Print Statements 9. if Tests if Statements Python Syntax Rules Truth Tests 10. while and for Loops while Loops break, continue, pass, and the Loop else for Loops Loop Variations 11. Documenting Python Code The Python Documentation Interlude Common Coding Gotchas Part III Exercises Part IV. Functions 12. Function Basics Why Use Functions? Coding Functions A First Example: Definitions and Calls A Second Example: Intersecting Sequences 13. Scopes and Arguments Scope Rules The global Statement Scopes and Nested Functions Passing Arguments Special Argument Matching Modes 14. Advanced Function Topics Anonymous Functions: ]ambda Applying Functions to Arguments Mapping Functions Over Sequences Functional Programming Tools List Comprehensions Generators and Iterators Function Design Concepts Function Gotchas Part IV Exercises Part V. Modules 15. Modules: The Big Picture Why Use Modules? Python Program Architecture How Imports Work 16. Module Coding Basics Module Creation Module Usage Module Namespaces Reloading Modules 17. Module Packages Package Import Basics Package Import Example Why Use Package Imports? A Tale of Three Systems 18. Advanced Module Topics Data Hiding in Modules Enabling Future Language Features Mixed Usage Modes: __name__ and __main_. Changing the Module Search Path The import as Extension Module Design Concepts Module Gotchas Part V Exercises Part VI. Classes and OOP 19. OOP: The Big Picture Why Use Classes? OOP from 30,000 Feet 20. Class Coding Basics Classes Generate Multiple Instance Objects Classes Are Customized by Inheritance Classes CanIntercept Python Operators 21. Class Coding Details The Class Statement Methods Inheritance Operator Overloading Namespaces: The Whole Story 22. Designing with Classes Python and OOP Classes as Records OOP and Inheritance: "is-a' Relationships OOP and Composition: "has-a" Relationships OOP and Delegation Multiple Inheritance Classes Are Objects: Generic Object Factories Methods Are Objects: Bound or Unbound Documentation Strings Revisited Classes Versus Modules 23. Advanced Class Topics Extending Built-in Types Pseudo-Private Class Attributes "New Style" Classes in Python 2.2 Class Gotchas Part VI Exercises Part VII. Exceptions and Tools 24. Exception Basics Why Use Exceptions? Exception Handling: The Short Story The try/except/else Statement The try/finally Statement The raise Statement The assert Statement 25. Exception Objects String-Based Exceptions Class-Based Exceptions General raise Statement Forms 26. Oesigning with Exceptions Nesting Exception Handlers Exception Idioms Exception Design Tips Exception Gotchas Core Language Summary Part VII Exercises Part VIII. The Outer Layers 27. Common Tasks in Python Conversions, Numbers, and Comparisons Manipulating Strings Data Structure Manipulations Manipulating Files and Directories Intemet-Related Modules Executing Programs Debugging, Testing, Timing, Profiling Exercises 28. Frameworks An Automated Complaint System Interfacing with COM: Cheap Public Relations A Tkinter-Based GUI Editor for Managing Form Data Jython: The Felicitous Union of Python and Java Exercises 29. Python Resources Layers of Community The Process Services and Products The Legal Framework: The Python Software Foundation Software Popular Third-'Party Software Web Application Frameworks Tools for Python Developers Part IX. Appendixes A. Installation and Configuration B. Solutions to Exercises Index
·目录·内容简介·前言 </BODY
le width="100%">
| This book provides an introduction to the Python programming language. Python is a popular object-oriented language used for both standalone programs and scripting applications in a variety of domains. It is free, portable, powerful, and remarkably easy to use. |
| Whether you are new to programming or a professional developer, this book's goal is to bring you up to speed on the core Python language in a hurry. |
| About This Second Edition |
| In the four years after the first edition of this book was published in late 1998, there have been substantial changes in both the Python language and in the topics presented by the authors in Python training sessions. Although we have attempted to retain as much of the original version as possible, this new edition reflects recent changes in both Python and Python training. |
| On the language front, this edition has been thoroughly updated to reflect Python 2.2, and all changes to the language since publication of the first edition. In addition, discussion of anticipated changes in the upcoming 2.3 release have been incorporated throughout. Some of the major language topics for which you'll find new or expanded coverage in this edition are: |
| · List comprehension (Chapter 14) |
| · Class exceptions (Chapter 25) |
| · String methods (Chapter 5) |
| · Augmented assignment (Chapter 8) |
| · Classic, true, and floor division (Chapter 4) |
| · Package imports (Chapter 17) |
| · Nested function scopes (Chapter 13) |
| · Generators and iterators (Chapter 14) |
| · Unicode strings (Chapter 5) |
| · Subclass types (Chapters 7 and 23) |
| · Static and class methods (Chapter 23) |
| · Pseudo-private class attributes (Chapter 23) |
| · Extended print and import statements (Chapters 8 and 18) |
| · New built-ins such as zip and isinstance (Chapters 7 and 10) |
| · New-style classes (Chapter 23) |
| · New configuration and launch options, and .pth files (Chapter 3 and Appendix A) |
| · New development tools such as IDLE, Psyco, Py2exe, and Installer (Chapters 2, 3, and 29) |
| · New testing and documentation tools such as PyDoc, PyUnit, and doctest (Chapter 26) |
| Smaller language changes (e.g., long integer promotion, module export lists) appear throughout the book. Besides such language changes, we augmented the core lan- guage parts of this edition (Parts I-VII) with new topics and examples presented in the Python training sessions Mark has held in recent years. For example, you'll find: |
| · A new OOP introduction (Chapter 19) |
| · A new dynamic typing overview (Chapter 4) |
| · A new development tools summary (Chapter 26) |
| · New material on program architecture and execution (Chapters 2, 3, and 15) |
| · New coverage of documentation sources (Chapter 11) |
| Many core language part additions and changes were made with beginners in mind. You'll also find that the coverage of many original core language topics has been substantially expanded in this edition, with new discussion and examples. Because this text has largely become the primary resource for learning the core Python language, we've taken liberties with making that coverage more complete than before, and added new use cases throughout. Likewise, we updated Part VIII to reflect recent Python application domains, and modem usage patterns. |
| In addition, this entire edition integrates a new set of Python tips and tricks, gleaned from both teaching classes over the last seven years, and using Python for real work over the last decade. The exercises have been updated and expanded to reflect current Python practice, new language features, and common beginner mistakes we've witnessed first-hand in recent years. Overall, this edition is bigger, both because Python is bigger, and because we've added context that has proved to be important in practice. |
| To accommodate the fact that this edition is more complete, we've split most of the original chapters into bite-sized chunks. That is, we've reorganized the core language section into many multichapter parts, to make the material easier to tackle. Types and statements, for instance, are now two top-level parts, with one chapter for each major type and statement topic. This new structure is designed to allow us to say more, without intimidating readers. In the process, exercises and gotchas were moved from chapter ends to part ends; they now appear at the end of the last chapter in each part. |
| Despite all the new topics, this book is still oriented toward Python newcomers, and is designed to be a first Python text for programmers.* It retains much of the first edition's material, structure, and focus. Where appropriate, we have expanded introductions for newcomers, and isolated the more advanced new topics from the main thread of discussion to avoid obscuring the fundamentals. Moreover, because it is largely based on time-tested training experience and materials, this edition, like the first, can still serve as a self-paced introductory Python class. |
| There are none to speak of, really. This book has been used successfully by both absolute beginners, and crusty programming veterans. In general, though, we have found that any exposure to programming or scripting before this text can be helpful, even if not required for every reader. |
| This book is designed to be an introductory level Python text for programmers. It may not be an ideal text for someone who has never touched a computer before (for instance, we're not going to spend any time explaining what a computer is), but we haven't made many assumptions about your programming background or education. |
| On the other hand, we won't insult readers by assuming they are "dummies" either, whatever that means; it's easy to do useful things in Python, and we hope to show you how. The text occasionally contrasts Python with languages such as C, C++, Java, and Pascal, but you can safely ignore these comparisons if you haven't used such languages in the past. |
| One thing we should probably mention up front: Python's creator, Guido van Rossum, named it after the BBC comedy series Monty Python's Flying Circus. This legacy has inevitably added a humorous flavor to many Python examples. For instance, the traditional "foo" and "bar" become "spam" and "eggs" in the Python world, and in some of the code you'll see in this book. The occasional "Brian," "Ni," and "shrubbery" likewise owe their appearances to this namesake. You don't need to be familiar with the series to make sense of such examples (symbols are symbols), but it can't hurt. |
| Although this book covers all the essentials of the Python language, we've kept its scope narrow in the interest of speed and size. To keep things simple, this book focuses on core concepts, uses small and self-contained examples to illustrate points, and sometimes omits the small details that are readily available in reference manuals. Because of that, this book is probably best described as both an introduction and a stepping stone to more advanced and complete texts. |
| For example, we won't say much about Python/C integration--a complex topic, which is nevertheless central to many Python-based systems. We also won't talk much about Python's history or development processes. And popular Python applications such as GUIs, system tools, and network scripting get only a short survey, if they are mentioned at all. Naturally, this scope misses some of the big picture. |
| By and large, Python is about raising the quality bar a few notches in the scripting world. Some of its ideas require more context than can be provided here, and we'd be remiss if we didn't recommend further study after you finish this book. We hope that most readers of this book will eventually go on to gain a more complete understanding of application-level programming from other texts. |
| Because of its beginners' focus, Learning Python is designed to be naturally complemented by O'Reilly's other Python books. For instance, Programming Python, Second Edition provides larger and more advanced application-level examples, and was explicitly designed to be a follow-up text to the one you are reading now. Roughly, the second editions of Learning Python and Programming Python reflect the two halves of Mark's training materials--the core language and applications programming. In addition, O'Reilly's Python Pocket Reference, Second Edition, serves as a quick reference supplement for looking up the fine details we will largely skip here. |
| Other followup Python books can also help provide additional examples, explore specific Python domains, and serve as references. We recommend O'Reilly's Python in a Nutshell and New Riders' Python Essential Reference as references, and |
| O'Reilly's Python Cookbook as an example library. Regardless of which books you choose, you should keep in mind that the rest of the Python story requires studying examples that are more realistic than there is space for here. There are roughly 40 English language Python books available today, along with a few dozen foreign language texts. Because books are a subjective experience, we invite you to browse all available texts to find one that suits your needs. |
| But despite its limited scope (and perhaps because of it), we think you'll find this book to be a good first text on Python. You'll learn everything you need to get started writing useful standalone Python programs and scripts. By the time you've finished this book, you will have learned not only the language itself, but also how to apply it to day-to-day tasks. And you'll be equipped to tackle more advanced topics and examples as they come your way. |
| This Book's Style and Structure |
| Much of this book is based on training materials developed for a three-day hands-on Python course. You'll find exercises at the end of the last chapter of the core language parts, with solutions to all exercises in Appendix B. The exercises are designed to get you coding right away, and are usually one of the highlights of the course. |
| We strongly recommend working through the exercises along the way, not only to gain Python programming experience, but also because some exercises raise issues not covered elsewhere in the book. The solutions in Appendix B should help if you get stuck (and we encourage you to "cheat" as much and as often as you like). Naturally, you'll need to install Python to run the exercises. |
| Because this text is designed to introduce language basics quickly, we've organized the presentation by major language features, not examples. We'll take a bottom-up approach here: from built-in object types, to statements, to program units, and so on. Each chapter is fairly self-contained, but later chapters use ideas introduced in earlier ones (e.g., by the time we get to classes, we'll assume you know how to write functions), so a linear reading makes the most sense. From a broader perspective, this book is divided into the following functional areas, and their corresponding parts. |
| This portion of the book presents the Python language, in a bottom-up fashion. It is organized with one part per major language feature--types, functions, and so forth--and most of the examples are small and self-contained (some might also call the examples in this section artificial, but they illustrate the points we're out to make). This section represents the bulk of the text, which tells you something about the focus of the book. It is composed of the following parts: |
| We begin with a general overview of Python, that answers commonly asked initial questions--why people use the language, what it's useful for, and so on. The first chapter introduces the major ideas underlying the technology, to give you some background context. This part then begins the technical material of the book, by exploring the ways that both you and Python run programs. Its goal is to give you just enough information to be able to work along with later examples and exercises. If you need more help getting started, additional configuration details are available in Appendix A. |
| Part II, Types and Operations |
| Next, we begin our tour of the Python language, by studying Python's major built-in object types in depth: numbers, lists, dictionaries, and so on. You can get a lot done in Python with these tools alone. |
| Part III, Statements and Syntax |
| The next part moves on to introduce Python's statements--the code you type to create and process objects in Python. It also presents Python's general syntax model. |
| This part begins our look at Python's higher-level program structure tools. Functions turn out to be a simple way to package code for reuse. |
| Python modules let you organize statements and functions into larger components, and this part illustrates how to create, use, and reload modules. |
| Here we explore Python's object-oriented programming (OOP) tool, the class. As you'll see, OOP in Python is mostly about looking up names in linked objects. |
| Part VII, Exceptions and Tools |
| We wrap up the core language coverage of this book section with a look at Python's exception handling model and statements, and a brief overview of development tools. This comes last, because exceptions can be classes if you want them to be. |
| Part VIII samples Python's built-in tools, and puts them to use in a collection of small example programs. Common tasks are demonstrated in Python to give you some realworld context, using both the language itself, and its standard libraries and tools. |
| Chapter 27, Common Tasks in Python |
| This chapter presents a selection of the modules and functions that are included in the default Python installation. By definition, they comprise the minimum set of modules you can reasonably expect any Python user to have access to. Knowing |
| the contents of this standard toolset will likely save you weeks of work. |
| This chapter presents a few real applications. By building on the language core explained in earlier parts and the built-in tools described in Chapter 27, we present many small but useful programs that show how to put it all together. We cover three areas that are of interest to most Python users: basic tasks, text |
| processing, and system interfaces. We close with a brief discussion of Jython, the Java port of Python, and a substantial Jython program. |
| Chapter 29, Python Resources |
| This chapter discusses the layers of the Python community and specialized libraries that are either part of the standard Python distribution or freely available from third parties. |
| The book ends with appendixes that give platform-specific tips for using Python on various platforms (Appendix A), and provide solutions to exercises that appear at the end of the last chapter in each part (Appendix B). Note that the index and table of contents can be used to hunt for details, but there are no reference appendixes in this book. As mentioned earlier, the Python Pocket Reference, Second Edition (O'Reilly), as well as other books and the free Python reference manuals maintained at http:// www.python.org, fill in syntax and built-in tool details. |
| Improvements happen (and so do mis^H^H^H typos). Updates, supplements, and corrections for this book will be maintained (or referenced) on the Web at one of the following sites: |
| · http://www, oreilly.com (O'Reilly's site) |
| · http://www, rmi. net/~lutz (Mark's site) |
| · http://starship.python.net/~da (David's site) |
| · http://www.python.org (Python's main site) |
| · http://www, rmi.net/~lutz/about-lp, html (book's web page) |
| If we could be more clairvoyant, we would, but the Web changes faster than printed books. |
| This book uses the following typographical conventions: |
| For email addresses, filenames, URLs, for emphasizing new terms when first introduced, and for some comments within code sections |
| Shows the contents of files or the output from commands and to designate modules, methods, statements, and commands |
| In code sections to show commands or text that would be typed |
| Shows replaceables in code sections |
| Represents syntactic units that you replace with real code |