Dorawebhosting.s3-website-us-east-1.amazonaws.com
Part I. Getting Started1. A Python Q&A Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsWhy 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 And More: Gaming, Images, Data Mining, Robots, Excel... How Is Python Developed and Supported? Open Source Tradeoffs What Are Python’s Technical Strengths? It’s Object-Oriented and Functional It’s Free It’s Portable It’s Powerful It’s Mixable It’s Relatively Easy to Use It’s Relatively Easy to Learn It’s Named After Monty Python How Does Python Stack Up to Language X? 2. How Python Runs Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 minsIntroducing the Python Interpreter Program Execution The Programmer’s View Python’s View Execution Model Variations Python Implementation Alternatives Execution Optimization Tools Frozen Binaries Future Possibilities? 3. How You Run Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 minsThe Interactive Prompt Starting an Interactive Session The System Path New Windows Options in .: PATH, Launcher Where to Run: Code Directories What Not to Type: Prompts and Comments Running Code Interactively Why the Interactive Prompt? Usage Notes: The Interactive Prompt System Command Lines and Files A First Script Running Files with Command Lines Command-Line Usage Variations Usage Notes: Command Lines and Files Unix-Style Executable Scripts: #! Unix Script Basics The Unix env Lookup Trick The Python . Windows Launcher: #! Comes to Windows Clicking File Icons Icon-Click Basics Clicking Icons on Windows The input Trick on Windows Other Icon-Click Limitations Module Imports and Reloads Import and Reload Basics The Grander Module Story: Attributes Usage Notes: import and reload Using exec to Run Module Files The IDLE User Interface IDLE Startup Details IDLE Basic Usage IDLE Usability Features Advanced IDLE Tools Usage Notes: IDLE Other IDEs Other Launch Options Embedding Calls Frozen Binary Executables Text Editor Launch Options Still Other Launch Options Future Possibilities? Which Option Should I Use? Part II. Types and Operations4. Introducing Python Object Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsThe Python Conceptual Hierarchy 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 Unicode Strings Pattern Matching Lists Sequence Operations Type-Specific Operations Bounds Checking Nesting Comprehensions Dictionaries Mapping Operations Nesting Revisited Missing Keys: if Tests Sorting Keys: for Loops Iteration and Optimization Tuples Why Tuples? Files Binary Bytes Files Unicode Text Files Other File-Like Tools Other Core Types How to Break Your Code’s Flexibility User-Defined Classes And Everything Else 5. Numeric Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 minsNumeric 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 Hex, Octal, Binary: Literals and Conversions 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 6. The Dynamic Typing Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 minsThe 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 7. String Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsThis Chapter’s Scope Unicode: The Short Story String Basics String Literals Single- and Double-Quoted Strings Are the Same Escape Sequences Represent Special Characters Raw Strings Suppress Escapes Triple Quotes Code Multiline Block Strings Strings in Action Basic Operations Indexing and Slicing String Conversion Tools Changing Strings I String Methods Method Call Syntax Methods of Strings String Method Examples: Changing Strings II String Method Examples: Parsing Text Other Common String Methods in Action The Original string Module’s Functions (Gone in .X) String Formatting Expressions Formatting Expression Basics Advanced Formatting Expression Syntax Advanced Formatting Expression Examples Dictionary-Based Formatting Expressions String Formatting Method Calls Formatting Method Basics Adding Keys, Attributes, and Offsets Advanced Formatting Method Syntax Advanced Formatting Method Examples Comparison to the % Formatting Expression Why the Format Method? General Type Categories Types Share Operation Sets by Categories Mutable Types Can Be Changed in Place 8. Lists and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsLists 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 More Dictionary Methods Example: Movie Database Dictionary Usage Notes Other Ways to Make Dictionaries Dictionary Changes in Python .X and . 9. Tuples, Files, and Everything Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsTuples Tuples in Action Why Lists and Tuples? Records Revisited: Named Tuples Files Opening Files Using Files Files in Action Text and Binary Files: The Short Story Storing Python Objects in Files: Conversions Storing Native Python Objects: pickle Storing Python Objects in JSON Format Storing Packed Binary Data: struct File Context Managers Other File Tools Core Types Review and Summary Object Flexibility References Versus Copies Comparisons, Equality, and Truth 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 Part III. Statements and Syntax10. Introducing Python Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 minsThe Python Conceptual Hierarchy Revisited Python’s Statements 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 11. Assignments, Expressions, and Prints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 minsAssignment Statements Assignment Statement Forms Sequence Assignments Extended Sequence Unpacking in Python .X Multiple-Target Assignments Augmented Assignments Variable Name Rules Expression Statements Expression Statements and In-Place Changes Print Operations The Python .X print Function The Python .X print Statement Print Stream Redirection Version-Neutral Printing 12. if Tests and Syntax Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 minsif Statements General Format Basic Examples Multiway Branching Python Syntax Revisited Block Delimiters: Indentation Rules Statement Delimiters: Lines and Continuations A Few Special Cases Truth Values and Boolean Tests The if/else Ternary Expression 13. while and for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 minswhile 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: range Sequence Scans: while and range Versus for Sequence Shufflers: range and len Nonexhaustive Traversals: range Versus Slices Changing Lists: range Versus Comprehensions Parallel Traversals: zip and map Generating Both Offsets and Items: enumerate 14. Iterations and Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 minsIterations: A First Look The Iteration Protocol: File Iterators Manual Iteration: iter and next Other Built-in Type Iterables List Comprehensions: A First Detailed Look List Comprehension Basics Using List Comprehensions on Files Extended List Comprehension Syntax Other Iteration Contexts New Iterables in Python .X Impacts on .X Code: Pros and Cons The range Iterable The map, zip, and filter Iterables Multiple Versus Single Pass Iterators Dictionary View Iterables Other Iteration Topics 14 . Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 minsWhy 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 15. Scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsPython Scope Basics Scope Details Name Resolution: The LEGB Rule Scope Example The Built-in Scope The global Statement Program Design: Minimize Global Variables Program Design: Minimize Cross-File Changes Other Ways to Access Globals Scopes and Nested Functions Nested Scope Details Nested Scope Examples Factory Functions: Closures Retaining Enclosing Scope State with Defaults The nonlocal Statement in .X nonlocal Basics nonlocal in Action Why nonlocal? State Retention Options State with nonlocal: .X only State with Globals: A Single Copy Only State with Classes: Explicit Attributes (Preview) State with Function Attributes: .X and .X 16. Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsArgument-Passing Basics Arguments and Shared References Avoiding Mutable Argument Changes Simulating Output Parameters and Multiple Results Special Argument-Matching Modes Argument Matching Basics Argument Matching Syntax The Gritty Details Keyword and Default Examples Arbitrary Arguments Examples Python .X Keyword-Only Arguments The min Wakeup Call! Full Credit Bonus Points The Punch Line... Generalized Set Functions Emulating the Python .X print Function Using Keyword-Only Arguments 17. Advanced Function Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsFunction Design Concepts Recursive Functions Summation with Recursion Coding Alternatives Loop Statements Versus Recursion Handling Arbitrary Structures Function Objects: Attributes and Annotations Indirect Function Calls: “First Class” Objects Function Introspection Function Attributes Function Annotations in .X Anonymous Functions: lambda lambda Basics Why Use lambda? How (Not) to Obfuscate Your Python Code Scopes: lambdas Can Be Nested Too Functional Programming Tools Mapping Functions over Iterables: map Selecting Items in Iterables: filter Combining Items in Iterables: reduce 18. Comprehensions and Generations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsList Comprehensions and Functional Tools List Comprehensions Versus map Adding Tests and Nested Loops: filter Example: List Comprehensions and Matrixes Don’t Abuse List Comprehensions: KISS Generator Functions and Expressions Generator Functions: yield Versus return Generator Expressions: Iterables Meet Comprehensions Generator Functions Versus Generator Expressions Generators Are Single-Iteration Objects Generation in Built-in Types, Tools, and Classes Example: Generating Scrambled Sequences Don’t Abuse Generators: EIBTI Example: Emulating zip and map with Iteration Tools Comprehension Syntax Summary Scopes and Comprehension Variables Comprehending Set and Dictionary Comprehensions Extended Comprehension Syntax for Sets and Dictionaries 19. The Benchmarking Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsTiming Iteration Alternatives Timing Module: Homegrown Timing Script Timing Results Timing Module Alternatives Other Suggestions Timing Iterations and Pythons with timeit Basic timeit Usage Benchmark Module and Script: timeit Benchmark Script Results More Fun with Benchmarks Other Benchmarking Topics: pystones Function Gotchas Local Names Are Detected Statically Defaults and Mutable Objects Functions Without returns Miscellaneous Function Gotchas Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part IV Exercises Part V. Modules and Packages21. Modules: The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsWhy Use Modules? Python Program Architecture How to Structure a Program Imports and Attributes Standard Library Modules How Imports Work . Find It . Compile It (Maybe) . Run It Byte Code Files: __pycache__ in Python .+ Byte Code File Models in Action The Module Search Path Configuring the Search Path Search Path Variations The sys.path List Module File Selection 22. Module Coding Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsModule Creation Module Filenames Other Kinds of Modules Module Usage The import Statement The from Statement The from * Statement Imports Happen Only Once import and from Are Assignments import and from Equivalence Potential Pitfalls of the from Statement Module Namespaces Files Generate Namespaces Namespace Dictionaries: __dict__ Attribute Name Qualification Imports Versus Scopes Namespace Nesting Reloading Modules reload Basics reload Example 23. Module Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 minsPackage 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 .X Relative Import Basics Why Relative Imports? The Scope of Relative Imports Module Lookup Rules Summary Relative Imports in Action Pitfalls of Package-Relative Imports: Mixed Use Python . Namespace Packages Namespace Package Semantics Impacts on Regular Packages: Optional __init__.py Namespace Packages in Action Namespace Package Nesting Files Still Have Precedence over Directories 24. Advanced Module Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 minsModule Design Concepts Data Hiding in Modules Minimizing from * Damage: _X and __all__ Enabling Future Language Features: __future__ Mixed Usage Modes: __name__ and __main__ Unit Tests with __name__ Example: Dual Mode Code Currency Symbols: Unicode in Action Docstrings: Module Documentation at Work Changing the Module Search Path The as Extension for import and from Example: Modules Are Objects Importing Modules by Name String Running Code Strings Direct Calls: Two Options Example: Transitive Module Reloads A Recursive Reloader Alternative Codings Module Gotchas Module Name Clashes: Package and Package-Relative Imports Statement Order Matters in Top-Level Code from Copies Names but Doesn’t Link from * Can Obscure the Meaning of Variables reload May Not Impact from Imports reload, from, and Interactive Testing Recursive from Imports May Not Work Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part V Exercises Part VI. Classes and OOP25. OOP: The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60 mins Why Use Classes? OOP from , Feet Attribute Inheritance Search Classes and Instances Method Calls Coding Class Trees Operator Overloading OOP Is About Code Reuse 26. Class Coding Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsClasses Generate Multiple Instance Objects Class Objects Provide Default Behavior Instance Objects Are Concrete Items A First Example Classes Are Customized by Inheritance A Second Example Classes Are Attributes in Modules Classes Can Intercept Python Operators A Third Example Why Use Operator Overloading? The World’s Simplest Python Class Records Revisited: Classes Versus Dictionaries 27. A More Realistic Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsStep : Making Instances Coding Constructors Testing As You GoUsing Code Two Ways Step : Adding Behavior Methods Coding Methods Step : Operator Overloading Providing Print Displays Step : Customizing Behavior by Subclassing Coding Subclasses Augmenting Methods: The Bad Way Augmenting Methods: The Good Way Polymorphism in Action Inherit, Customize, and Extend OOP: The Big Idea Step : Customizing Constructors, Too OOP Is Simpler Than You May Think Other Ways to Combine Classes Step : Using Introspection Tools Special Class Attributes A Generic Display Tool Instance Versus Class Attributes Name Considerations in Tool Classes Our Classes’ Final Form Step (Final): Storing Objects in a Database Pickles and Shelves Storing Objects on a Shelve Database Exploring Shelves Interactively Updating Objects on a Shelve Future Directions 28. Class Coding Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsThe class Statement General Form Example Methods Method Example Calling Superclass Constructors Other Method Call Possibilities Inheritance Attribute Tree Construction Specializing Inherited Methods Class Interface Techniques Table of Contents | xxiAbstract Superclasses Namespaces: The Conclusion Simple Names: Global Unless Assigned Attribute Names: Object Namespaces The “Zen” of Namespaces: Assignments Classify Names Nested Classes: The LEGB Scopes Rule Revisited Namespace Dictionaries: Review Namespace Links: A Tree Climber Documentation Strings Revisited Classes Versus Modules Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers 29. Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsThe Basics Constructors and Expressions: __init__ and __sub__ Common Operator Overloading Methods Indexing and Slicing: __getitem__ and __setitem__ Intercepting Slices Slicing and Indexing in Python .X But .X’s __index__ Is Not Indexing! Index Iteration: __getitem__ Iterable Objects: __iter__ and __next__ User-Defined Iterables Multiple Iterators on One Object Coding Alternative: __iter__ plus yield Membership: __contains__, __iter__, and __getitem__ Attribute Access: __getattr__ and __setattr__ Attribute Reference Attribute Assignment and Deletion Other Attribute Management Tools Emulating Privacy for Instance Attributes: Part String Representation: __repr__ and __str__ Why Two Display Methods? Display Usage Notes Right-Side and In-Place Uses: __radd__ and __iadd__ Right-Side Addition In-Place Addition Call Expressions: __call__ Function Interfaces and Callback-Based Code Comparisons: __lt__, __gt__, and Others The __cmp__ Method in Python .X xxii | Table of ContentsBoolean Tests: __bool__ and __len__ Boolean Methods in Python .X Object Destruction: __del__ Destructor Usage Notes 28. Designing with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsPython and OOP Polymorphism Means Interfaces, Not Call Signatures OOP and Inheritance: “Is-a” Relationships OOP and Composition: “Has-a” Relationships Stream Processors Revisited OOP and Delegation: “Wrapper” Proxy Objects Pseudoprivate Class Attributes Name Mangling Overview Why Use Pseudoprivate Attributes? Methods Are Objects: Bound or Unbound Unbound Methods Are Functions in .X Bound Methods and Other Callable Objects Classes Are Objects: Generic Object Factories Why Factories? Multiple Inheritance: “Mix-in” Classes Coding Mix-in Display Classes Other Design-Related Topics 29. Advanced Class Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 minsExtending Built-in Types Extending Types by Embedding Extending Types by Subclassing The “New Style” Class Model Just How New Is New-Style? New-Style Class Changes Attribute Fetch for Built-ins Skips Instances Type Model Changes All Classes Derive from “object” Diamond Inheritance Change More on the MRO: Method Resolution Order Example: Mapping Attributes to Inheritance SourcesNew-Style Class Extensions Slots: Attribute Declarations Properties: Attribute Accessors __getattribute__ and Descriptors: Attribute Tools Other Class Changes and Extensions Static and Class Methods Why the Special Methods? Static Methods in .X and .X Static Method Alternatives Using Static and Class Methods Counting Instances with Static Methods Counting Instances with Class Methods Decorators and Metaclasses: Part Function Decorator Basics A First Look at User-Defined Function Decorators A First Look at Class Decorators and Metaclasses For More Details The super Built-in Function: For Better or Worse? The Great super Debate Traditional Superclass Call Form: Portable, General Basic super Usage and Its Tradeoffs The super Upsides: Tree Changes and Dispatch Runtime Class Changes and super Cooperative Multiple Inheritance Method Dispatch The super Summary Class Gotchas Changing Class Attributes Can Have Side Effects Changing Mutable Class Attributes Can Have Side Effects, Too Multiple Inheritance: Order Matters Scopes in Methods and Classes Miscellaneous Class Gotchas KISS Revisited: “Overwrapping-itis” Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part VI Exercises Part VII. Exceptions and Tools30. Exception Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 minsWhy Use Exceptions? Exception Roles Exceptions: The Short Story Default Exception Handler Catching Exceptions Raising Exceptions User-Defined Exceptions Termination Actions 31. Exception Coding Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 minsThe try/except/else Statement How try Statements Work try Statement Clauses The try else Clause Example: Default Behavior Example: Catching Built-in Exceptions The try/finally Statement Example: Coding Termination Actions with try/finally Unified try/except/finally Unified try Statement Syntax Combining finally and except by Nesting Unified try Example The raise Statement Raising Exceptions Scopes and try except Variables Propagating Exceptions with raise Python .X Exception Chaining: raise from The assert Statement Example: Trapping Constraints (but Not Errors!) with/as Context Managers Basic Usage The Context Management Protocol Multiple Context Managers in ., ., and Later 32. Exception Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 minsExceptions: Back to the Future String Exceptions Are Right Out! Class-Based Exceptions Coding Exceptions ClassesWhy Exception Hierarchies? Built-in Exception Classes Built-in Exception Categories Default Printing and State Custom Print Displays Custom Data and Behavior Providing Exception Details Providing Exception Methods 33. Designing with Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsNesting Exception Handlers Example: Control-Flow Nesting Example: Syntactic Nesting Exception Idioms Breaking Out of Multiple Nested Loops: “go to” Exceptions Aren’t Always Errors Functions Can Signal Conditions with raise Closing Files and Server Connections Debugging with Outer try Statements Running In-Process Tests More on sys.exc_info Displaying Errors and Tracebacks Exception Design Tips and Gotchas What Should Be Wrapped Catching Too Much: Avoid Empty except and Exception Catching Too Little: Use Class-Based Categories Core Language Summary The Python Toolset Development Tools for Larger Projects Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Test Your Knowledge: Part VII Exercises Part VIII. Advanced Topics34. Unicode and Byte Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 minsString Changes in .X String BasicsCharacter Encoding Schemes How Python Stores Strings in Memory Python’s String Types Text and Binary Files Coding Basic Strings Python .X String Literals Python .X String Literals String Type Conversions Coding Unicode Strings Coding ASCII Text Coding Non-ASCII Text Encoding and Decoding Non-ASCII text Other Encoding Schemes Byte String Literals: Encoded Text Converting Encodings Coding Unicode Strings in Python .X Source File Character Set Encoding Declarations Using .X bytes Objects Method Calls Sequence Operations Other Ways to Make bytes Objects Mixing String Types Using .X/.+ bytearray Objects bytearrays in Action Python .X String Types Summary Using Text and Binary Files Text File Basics Text and Binary Modes in .X and .X Type and Content Mismatches in .X Using Unicode Files Reading and Writing Unicode in .X Handling the BOM in .X Unicode Files in .X Unicode Filenames and Streams Other String Tool Changes in .X The re Pattern-Matching Module The struct Binary Data Module The pickle Object Serialization Module XML Parsing Tools Chapter Summary Test Your Knowledge: Quiz Test Your Knowledge: Answers Table of Contents | xxvii35. Managed Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsWhy Manage Attributes? Inserting Code to Run on Attribute Access Properties The Basics A First Example Computed Attributes Coding Properties with Decorators Descriptors The Basics A First Example Computed Attributes Using State Information in Descriptors How Properties and Descriptors Relate __getattr__ and __getattribute__ The Basics A First Example Computed Attributes __getattr__ and __getattribute__ Compared Management Techniques Compared Intercepting Built-in Operation Attributes Example: Attribute Validations Using Properties to Validate Using Descriptors to Validate Using __getattr__ to Validate Using __getattribute__ to Validate 36. Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 minsWhat’s a Decorator? Managing Calls and Instances Managing Functions and Classes Using and Defining Decorators Why Decorators? The Basics Function Decorators Class Decorators Decorator Nesting Decorator Arguments Decorators Manage Functions and Classes, Too Coding Function Decorators Tracing Calls Decorator State Retention Options Class Blunders I: Decorating Methods Timing Calls Adding Decorator Arguments Coding Class Decorators Singleton Classes Tracing Object Interfaces Class Blunders II: Retaining Multiple Instances Decorators Versus Manager Functions Why Decorators? (Revisited) Managing Functions and Classes Directly Example: “Private” and “Public” Attributes Implementing Private Attributes Implementation Details I Generalizing for Public Declarations, Too Implementation Details II Open Issues Python Isn’t About Control Example: Validating Function Arguments The Goal A Basic Range-Testing Decorator for Positional Arguments Generalizing for Keywords and Defaults, Too Implementation Details Open Issues Decorator Arguments Versus Function Annotations Other Applications: Type Testing (If You Insist!) 37. Metaclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 minsTo Metaclass or Not to Metaclass Increasing Levels of “Magic” A Language of Hooks The Downside of “Helper” Functions Metaclasses Versus Class Decorators: Round The Metaclass Model Classes Are Instances of type Metaclasses Are Subclasses of Type Class Statement Protocol Declaring Metaclasses Declaration in .X Metaclass Dispatch in Both .X and .X Coding Metaclasses A Basic Metaclass Customizing Construction and Initialization Other Metaclass Coding Techniques Inheritance and Instance Metaclass Versus Superclass Inheritance: The Full Story Metaclass Methods Metaclass Methods Versus Class Methods Operator Overloading in Metaclass Methods Example: Adding Methods to Classes Manual Augmentation Metaclass-Based Augmentation Metaclasses Versus Class Decorators: Round Example: Applying Decorators to Methods Tracing with Decoration Manually Tracing with Metaclasses and Decorators Applying Any Decorator to Methods Metaclasses Versus Class Decorators: Round (and Last) ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.