Tải bản đầy đủ (.pdf) (1,214 trang)

Learning python 4th edition (covers python 2 6 and 3 x) 4204

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.4 MB, 1,214 trang )



Learning Python



FOURTH EDITION

Learning Python

Mark Lutz

Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo


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 (). For more information, contact our
corporate/institutional sales department: (800) 998-9938 or

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


To Vera.
You are my life.




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


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


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


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


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


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


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


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


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


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


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


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


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


Modules Are Objects: Metaprograms
Importing Modules by Name String
Transitive Module Reloads
Module Design Concepts
Module Gotchas

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

591
594
595
598
599
599
600
601
601
602
603
604
604
605
605

Part VI. Classes and OOP
25. OOP: The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
Why Use Classes?

OOP from 30,000 Feet
Attribute Inheritance Search
Classes and Instances
Class Method Calls
Coding Class Trees
OOP Is About Code Reuse
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers

612
613
613
615
616
616
619
622
622
622

26. Class Coding Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Classes 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

xx | Table of Contents

625
626
626
627
629
630
631
633
634
636
636


Classes Versus Dictionaries
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers

639
641
641
641

27. A More Realistic Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643

Step 1: Making Instances
Coding Constructors
Testing As You Go
Using Code Two Ways
Step 2: Adding Behavior Methods
Coding Methods
Step 3: Operator Overloading
Providing Print Displays
Step 4: 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 5: Customizing Constructors, Too
OOP Is Simpler Than You May Think
Other Ways to Combine Classes
Step 6: Using Introspection Tools
Special Class Attributes
A Generic Display Tool
Instance Versus Class Attributes
Name Considerations in Tool Classes
Our Classes’ Final Form
Step 7 (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

Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers

644
644
645
646
648
649
651
652
653
653
654
654
656
657
658
658
660
660
663
664
665
666
667
668
669
670

671
672
674
675
677
677
678

28. Class Coding Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
The class Statement
General Form

681
681
Table of Contents | xxi


Example
Methods
Method Example
Calling Superclass Constructors
Other Method Call Possibilities
Inheritance
Attribute Tree Construction
Specializing Inherited Methods
Class Interface Techniques
Abstract Superclasses
Python 2.6 and 3.0 Abstract Superclasses
Namespaces: The Whole Story
Simple Names: Global Unless Assigned

Attribute Names: Object Namespaces
The “Zen” of Python Namespaces: Assignments Classify Names
Namespace Dictionaries
Namespace Links
Documentation Strings Revisited
Classes Versus Modules
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers

682
684
685
686
686
687
687
687
689
690
692
693
693
693
694
696
699
701
703
703

703
704

29. Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
The Basics
Constructors and Expressions: __init__ and __sub__
Common Operator Overloading Methods
Indexing and Slicing: __getitem__ and __setitem__
Intercepting Slices
Index Iteration: __getitem__
Iterator Objects: __iter__ and __next__
User-Defined Iterators
Multiple Iterators on One Object
Membership: __contains__, __iter__, and __getitem__
Attribute Reference: __getattr__ and __setattr__
Other Attribute Management Tools
Emulating Privacy for Instance Attributes: Part 1
String Representation: __repr__ and __str__
Right-Side and In-Place Addition: __radd__ and __iadd__
In-Place Addition
Call Expressions: __call__
Function Interfaces and Callback-Based Code
Comparisons: __lt__, __gt__, and Others

xxii | Table of Contents

705
706
706
708

708
710
711
712
714
716
718
719
720
721
723
725
725
727
728


The 2.6 __cmp__ Method (Removed in 3.0)
Boolean Tests: __bool__ and __len__
Object Destruction: __del__
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers

729
730
732
733
734
734


30. Designing with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
Python and OOP
Overloading by Call Signatures (or Not)
OOP and Inheritance: “Is-a” Relationships
OOP and Composition: “Has-a” Relationships
Stream Processors Revisited
OOP and Delegation: “Wrapper” Objects
Pseudoprivate Class Attributes
Name Mangling Overview
Why Use Pseudoprivate Attributes?
Methods Are Objects: Bound or Unbound
Unbound Methods are Functions in 3.0
Bound Methods and Other Callable Objects
Multiple Inheritance: “Mix-in” Classes
Coding Mix-in Display Classes
Classes Are Objects: Generic Object Factories
Why Factories?
Other Design-Related Topics
Chapter Summary
Test Your Knowledge: Quiz
Test Your Knowledge: Answers

737
738
739
740
742
745
747

748
748
750
752
754
756
757
768
769
770
770
770
771

31. Advanced Class Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
Extending Built-in Types
Extending Types by Embedding
Extending Types by Subclassing
The “New-Style” Class Model
New-Style Class Changes
Type Model Changes
Diamond Inheritance Change
New-Style Class Extensions
Instance Slots
Class Properties
__getattribute__ and Descriptors
Metaclasses
Static and Class Methods

773

774
775
777
778
779
783
788
788
792
794
794
795
Table of Contents | xxiii


×