1. Trang chủ
  2. » Công Nghệ Thông Tin

Learning python

519 46 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 519
Dung lượng 2,61 MB

Nội dung

This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] • • • • • • Table of Contents Index Reviews Reader Reviews Errata Academic Learning Python, 2nd Edition By David Ascher, Mark Lutz Publisher: O'Reilly Pub Date: December 2003 ISBN: 0-596-00281-5 Pages: 620 Learning Python, Second Edition offers programmers a comprehensive learning tool for Python and object-oriented programming Thoroughly updated, this guide introduces the basic elements of the latest release of Python 2.3 and covers new features, such as list comprehensions, nested scopes, and iterators/generators [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] • • • • • • Table of Contents Index Reviews Reader Reviews Errata Academic Learning Python, 2nd Edition By David Ascher, Mark Lutz Publisher: O'Reilly Pub Date: December 2003 ISBN: 0-596-00281-5 Pages: 620 Copyright Dedication Preface About This Second Edition Prerequisites This Book's Scope This Book's Style and Structure Book Updates Font Conventions About the Programs in This Book Using Code Examples How to Contact Us Acknowledgments Part I: Getting Started Chapter A Python Q&A Session Section 1.1 Why Do People Use Python? Section 1.2 Is Python a Scripting Language? Section 1.3 Okay, But What's the Downside? Section 1.4 Who Uses Python Today? Section 1.5 What Can I Do with Python? Section 1.6 What Are Python's Technical Strengths? Section 1.7 How Does Python Stack Up to Language X? Chapter How Python Runs Programs Section 2.1 Introducing the Python Interpreter This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 2.1 Introducing the Python Interpreter Section 2.2 Program Execution Section 2.3 Execution Model Variations Chapter How You Run Programs Section 3.1 Interactive Coding Section 3.2 System Command Lines and Files Section 3.3 Clicking Windows File Icons Section 3.4 Module Imports and Reloads Section 3.5 The IDLE User Interface Section 3.6 Other IDEs Section 3.7 Embedding Calls Section 3.8 Frozen Binary Executables Section 3.9 Text Editor Launch Options Section 3.10 Other Launch Options Section 3.11 Future Possibilities? Section 3.12 Which Option Should I Use? Section 3.13 Part I Exercises Part II: Types and Operations Chapter Numbers Section 4.1 Python Program Structure Section 4.2 Why Use Built-in Types? Section 4.3 Numbers Section 4.4 Python Expression Operators Section 4.5 Numbers in Action Section 4.6 The Dynamic Typing Interlude Chapter Strings Section 5.1 String Literals Section 5.2 Strings in Action Section 5.3 String Formatting Section 5.4 String Methods Section 5.5 General Type Categories Chapter Lists and Dictionaries Section 6.1 Lists Section 6.2 Lists in Action Section 6.3 Dictionaries Section 6.4 Dictionaries in Action Chapter Tuples, Files, and Everything Else Section 7.1 Tuples Section 7.2 Files Section 7.3 Type Categories Revisited Section 7.4 Object Generality Section 7.5 References Versus Copies Section 7.6 Comparisons, Equality, and Truth Section 7.7 Python's Type Hierarchies Section 7.8 Other Types in Python Section 7.9 Built-in Type Gotchas Section 7.10 Part II Exercises Part III: Statements and Syntax Chapter Assignment, Expressions, and Print Section 8.1 Assignment Statements Section 8.2 Expression Statements Section 8.3 Print Statements Chapter if Tests This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 9.1 if Statements Section 9.2 Python Syntax Rules Section 9.3 Truth Tests Chapter 10 while and for Loops Section 10.1 while Loops Section 10.2 break, continue, pass, and the Loop else Section 10.3 for Loops Section 10.4 Loop Variations Chapter 11 Documenting Python Code Section 11.1 The Python Documentation Interlude Section 11.2 Common Coding Gotchas Section 11.3 Part III Exercises Part IV: Functions Chapter 12 Function Basics Section 12.1 Why Use Functions? Section 12.2 Coding Functions Section 12.3 A First Example: Definitions and Calls Section 12.4 A Second Example: Intersecting Sequences Chapter 13 Scopes and Arguments Section 13.1 Scope Rules Section 13.2 The global Statement Section 13.3 Scopes and Nested Functions Section 13.4 Passing Arguments Section 13.5 Special Argument Matching Modes Chapter 14 Advanced Function Topics Section 14.1 Anonymous Functions: lambda Section 14.2 Applying Functions to Arguments Section 14.3 Mapping Functions Over Sequences Section 14.4 Functional Programming Tools Section 14.5 List Comprehensions Section 14.6 Generators and Iterators Section 14.7 Function Design Concepts Section 14.8 Function Gotchas Section 14.9 Part IV Exercises Part V: Modules Chapter 15 Modules: The Big Picture Section 15.1 Why Use Modules? Section 15.2 Python Program Architecture Section 15.3 How Imports Work Chapter 16 Module Coding Basics Section 16.1 Module Creation Section 16.2 Module Usage Section 16.3 Module Namespaces Section 16.4 Reloading Modules Chapter 17 Module Packages Section 17.1 Package Import Basics Section 17.2 Package Import Example Section 17.3 Why Use Package Imports? Section 17.4 A Tale of Three Systems Chapter 18 Advanced Module Topics Section 18.1 Data Hiding in Modules Section 18.2 Enabling Future Language Features Section 18.3 Mixed Usage Modes: name and main This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 18.3 Mixed Usage Modes: name and main Section 18.4 Changing the Module Search Path Section 18.5 The import as Extension Section 18.6 Module Design Concepts Section 18.7 Module Gotchas Section 18.8 Part V Exercises Part VI: Classes and OOP Chapter 19 OOP: The Big Picture Section 19.1 Why Use Classes? Section 19.2 OOP from 30,000 Feet Chapter 20 Class Coding Basics Section 20.1 Classes Generate Multiple Instance Objects Section 20.2 Classes Are Customized by Inheritance Section 20.3 Classes Can Intercept Python Operators Chapter 21 Class Coding Details Section 21.1 The Class Statement Section 21.2 Methods Section 21.3 Inheritance Section 21.4 Operator Overloading Section 21.5 Namespaces: The Whole Story Chapter 22 Designing with Classes Section 22.1 Python and OOP Section 22.2 Classes as Records Section 22.3 OOP and Inheritance: "is-a" Relationships Section 22.4 OOP and Composition: "has-a" Relationships Section 22.5 OOP and Delegation Section 22.6 Multiple Inheritance Section 22.7 Classes Are Objects: Generic Object Factories Section 22.8 Methods Are Objects: Bound or Unbound Section 22.9 Documentation Strings Revisited Section 22.10 Classes Versus Modules Chapter 23 Advanced Class Topics Section 23.1 Extending Built-in Types Section 23.2 Pseudo-Private Class Attributes Section 23.3 "New Style" Classes in Python 2.2 Section 23.4 Class Gotchas Section 23.5 Part VI Exercises Part VII: Exceptions and Tools Chapter 24 Exception Basics Section 24.1 Why Use Exceptions? Section 24.2 Exception Handling: The Short Story Section 24.3 The try/except/else Statement Section 24.4 The try/finally Statement Section 24.5 The raise Statement Section 24.6 The assert Statement Chapter 25 Exception Objects Section 25.1 String-Based Exceptions Section 25.2 Class-Based Exceptions Section 25.3 General raise Statement Forms Chapter 26 Designing with Exceptions Section 26.1 Nesting Exception Handlers Section 26.2 Exception Idioms Section 26.3 Exception Design Tips This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Section 26.4 Exception Gotchas Section 26.5 Core Language Summary Section 26.6 Part VII Exercises Part VIII: The Outer Layers Chapter 27 Common Tasks in Python Section 27.1 Exploring on Your Own Section 27.2 Conversions, Numbers, and Comparisons Section 27.3 Manipulating Strings Section 27.4 Data Structure Manipulations Section 27.5 Manipulating Files and Directories Section 27.6 Internet-Related Modules Section 27.7 Executing Programs Section 27.8 Debugging, Testing, Timing, Profiling Section 27.9 Exercises Chapter 28 Frameworks Section 28.1 An Automated Complaint System Section 28.2 Interfacing with COM: Cheap Public Relations Section 28.3 A Tkinter-Based GUI Editor for Managing Form Data Section 28.4 Jython: The Felicitous Union of Python and Java Section 28.5 Exercises Chapter 29 Python Resources Section 29.1 Layers of Community Section 29.2 The Process Section 29.3 Services and Products Section 29.4 The Legal Framework: The Python Software Foundation Section 29.5 Software Section 29.6 Popular Third-Party Software Section 29.7 Web Application Frameworks Section 29.8 Tools for Python Developers Part IX: Appendixes Appendix A Installation and Configuration Section A.1 Installing the Python Interpreter Appendix B Solutions to Exercises Section B.1 Part I, Getting Started Section B.2 Part II, Types and Operations Section B.3 Part III, Statements and Syntax Section B.4 Part IV, Functions Section B.5 Part V, Modules Section B.6 Part VI, Classes and OOP Section B.7 Part VII, Exceptions and Tools Section B.8 Part VIII, The Outer Layers Colophon Index [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] Copyright Copyright © 2004, 1999 O'Reilly & Associates, Inc Printed in the United States of America Published by O'Reilly & Associates, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O'Reilly & Associates books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://safari.oreilly.com) For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly & Associates, Inc Learning Python, the image of a wood rat, and related trade dress are trademarks of O'Reilly & Associates, 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 & Associates, 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 authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] Dedication To the late Frank Willison, our mentor, friend, and first editor [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] Preface 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 [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] 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 (Chapter and Chapter 23) Static and class methods (Chapter 23) Pseudo-private class attributes (Chapter 23) Extended print and import statements (Chapter and Chapter 18) New built-ins such as zip and isinstance (Chapter and Chapter 10) New-style classes (Chapter 23) New configuration and launch options, and pth files (Chapter and Appendix A) New development tools such as IDLE, Psyco, Py2exe, and Installer (Chapter 2, Chapter 3, and Chapter 29) New testing and documentation tools such as PyDoc, PyUnit, and doctest (Chapter 11) Smaller language changes (e.g., long integer promotion, module export lists) appear throughout the book Besides such language changes, we augmented the core language parts of this edition (Part I-Part 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 (Chapter 2, Chapter 3, and Chapter 15) New coverage of documentation sources (Chapter 11) This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] packages imports modules parallel traversals parameters, functions parentheses in expressions Parrot project parsing arguments 2nd raise statements text pass statement passing keyword arguments PATH environment variable 2nd paths modules qualification search 2nd patterns built-in string methods design performance Perl language persistence pickle module 2nd 3rd 4th PIL (Python Imaging Library) piping polymorphism 2nd 3rd 4th portable ANSI C portable database APIs positive offsets, strings POSIX conventions precedence expressions rules (operators) print statements 2nd in files numbers privileges, executable scripts processing files 2nd lines number objects productivity profile module profiling programming AI architecture class trees code reuse comments databases documentation This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com dynamic typing model exceptions 2nd executing functions GUI hello world interpreter modules 2nd names numeric OOP string methods strings structure termination actions tools troubleshooting prompts compound statements file extensions indenting input (>>>) input ( ) interactive propagating exceptions 2nd properties classes lists syntax rules prototyping pseudo-private class attributes Psyco Just-in-Time compiler pth file directories PVM (Python Virtual Machine) PyDoc tools HTML reports Python Imaging Library (PIL) Python Virtual Machine (PVM) Python.NET PYTHONPATH variable directories PYTHONSTARTUP variable PythonWin PythonWorks [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] qualification getattr method names 2nd quality [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] raise statement 2nd random module ranges character lists loops rapid prototyping raw strings, suppressing escapes raw_input function 2nd re module 2nd re.compile( ) (strings) read stdin records classes as dictionaries recursive imports redirection output streams scripts references arguments assignments copying versus garbage collection in-place object changes shared regular expressions 2nd relationships, inheritance/OOP reloading modules attributes example general form impact from imports usage notes remainder operator repetition, one-level deep reports, PyDoc 2nd representations, strings reserved words return statements 2nd roles, exceptions rules LEGB open pairs scope syntax running Python embedded code, objects interactive command line interpreter module files Unix-style scripts runtime, def statements [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] saving text scope 2nd [See also namespaces]3rd 4th built-in imports lambdas LGB rule nested functions nesting 2nd rules scripting 2nd IDLE Internet languages PVM redirecting Unix-like wrapping searching exceptions inheritance modules packages paths, changing selection of chunk size of modules sending extra data in instances sequences embedding execution functions intersecting lists suppressing shared object references shared references 2nd shell tools shelve module shift operators short-circuit evaluation shutil module signatures, calls simple variables single-quoted strings size, object slicing 2nd 3rd assignments lists 2nd slots, instances software quality solutions to exercises sort method 2nd sorts, customizing source code, compiling This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com spaces in programs sparse data structures, dictionaries for special-case handling speed of development Stackless Python system stacks Standard Library modules standard manual set standards, docstrings statements assert assignment 2nd 3rd 4th compound defined delimiters expressions if order of print 2nd raise summary syntax troubleshooting truth tests try/except/else try/finally try/finally/termination actions while wrapping static local function variables static methods, new style classes statically nested scopes Stein, Greg str function stream processors stream redirection string module constants functions regular expressions problem replacement operation strings basic operations block categories of types changing, formatting codes constants, operations defined documentation 2nd exceptions formatting indexing 2nd lists literals methods modifying 2nd returning slicing 2nd This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com struct module format codes structure of programs subclasses 2nd 3rd subexpressions suffixes [See also extensions] complex numbers superclasses 2nd abstract constructors suppressing escape sequences Swing Java GUI toolkit syntactic nesting syntax apply function backslashes execution sequences open pairs statements syntax rules blocks 2nd compound statements spaces, comments statement delimiters variable names sys.modules dictionary sys.path dictionary sys.path list sys.stdout, writing to systems programming [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] tables, dictionaries tempfile module temporary files termination actions 2nd 3rd testing code equality exceptions if statements in-process tests, running interactive truth values text comments docstrings exceptions modifying strings parsing redirecting saving string methods text editors launch options modules time module timing Tk/Tkinter 2nd 3rd environment setting GUI tools built-in functions documentation expressions multiway branching numbers programming PyDoc shell top-level copies translation, Psyco Just-in-Time compiler trapping constraints traversals loops parallel trees 2nd triple-quoted strings 2nd troubleshooting classes code exceptions 2nd 3rd explicit conflict resolution functions icon clicks if statements This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com modules mutable argument changes objects truth values truth values objects testing try statement try/except/else statement try/finally statement try/except/else statement try/finally statement tuples assignment defined functions properties of sorting contents of types Built-in categories 2nd collection tuples constraints converting 2nd dynamic typing model files hierarchies iterators mutable 2nd names numbers objects reasons for built-in troubleshooting [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] unary operators unbound class methods Unicode strings Unix-like system scripts unpacking assignments unqualified names urllib module urlparse module URLs, urllib module usage notes 2nd user-defined docstrings user-defined exceptions, catching user-defined iterators [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] values default arguments 2nd functions object truth values truth values van Rossum, Guido variables assignments local name rules numbers simple variations, execution models viewing 2nd Visual Python [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] web pages, cgi module web site resources while loop whrandom module wide character strings win32com Dispatch function formletter.py program windows [See also interfaces] Windows automatic extensions icons windows IDLE wrapping statements writing [See also code] functions to sys.stdout [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] XML (Extensible Markup Language) 2nd 3rd [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com [ Team LiB ] [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] zip 2nd Zope [ Team LiB ] This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Brought to You by Like the book? Buy it! ... I Do with Python? Section 1.6 What Are Python' s Technical Strengths? Section 1.7 How Does Python Stack Up to Language X? Chapter How Python Runs Programs Section 2.1 Introducing the Python Interpreter... Started Chapter A Python Q&A Session Section 1.1 Why Do People Use Python? Section 1.2 Is Python a Scripting Language? Section 1.3 Okay, But What's the Downside? Section 1.4 Who Uses Python Today?... 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

Ngày đăng: 26/03/2019, 11:23