100% found this document useful (7 votes)
27 views

Learning Python 4th edition Mark Lutz pdf download

The document provides information about the fourth edition of 'Learning Python' by Mark Lutz, including details on its publication, contents, and various other related Python programming resources. It outlines the structure of the book, which includes sections on getting started, types and operations, and practical applications of Python. Additionally, it offers links to download the book and other related titles in different formats.

Uploaded by

nhongohanze
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (7 votes)
27 views

Learning Python 4th edition Mark Lutz pdf download

The document provides information about the fourth edition of 'Learning Python' by Mark Lutz, including details on its publication, contents, and various other related Python programming resources. It outlines the structure of the book, which includes sections on getting started, types and operations, and practical applications of Python. Additionally, it offers links to download the book and other related titles in different formats.

Uploaded by

nhongohanze
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Learning Python 4th edition Mark Lutz pdf

download

https://ebookname.com/product/learning-python-4th-edition-mark-
lutz/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Learning Python Third Edition Mark Lutz

https://ebookname.com/product/learning-python-third-edition-mark-
lutz/

Programming Python 4th Edition Mark Lutz

https://ebookname.com/product/programming-python-4th-edition-
mark-lutz/

Python Pocket Reference 4th ed Edition Mark Lutz

https://ebookname.com/product/python-pocket-reference-4th-ed-
edition-mark-lutz/

Success and Failure in Public Governance A Comparative


Analysis New Horizons in Public Policy First Edition
Mark Bovens

https://ebookname.com/product/success-and-failure-in-public-
governance-a-comparative-analysis-new-horizons-in-public-policy-
first-edition-mark-bovens/
Working with Ethnicity Race and Culture in Mental
Health A Handbook for Practitioners 1st Edition Hari
Sewell

https://ebookname.com/product/working-with-ethnicity-race-and-
culture-in-mental-health-a-handbook-for-practitioners-1st-
edition-hari-sewell/

Analytical Characterization of Aluminum Steel and


Superalloys 1st Edition D. Scott Mackenzie

https://ebookname.com/product/analytical-characterization-of-
aluminum-steel-and-superalloys-1st-edition-d-scott-mackenzie/

An Introduction to Forensic Linguistics 1st Edition


Malcolm Coulthard

https://ebookname.com/product/an-introduction-to-forensic-
linguistics-1st-edition-malcolm-coulthard/

A History of Russian Thought 1st Edition William


Leatherbarrow

https://ebookname.com/product/a-history-of-russian-thought-1st-
edition-william-leatherbarrow/

Water distribution systems 2nd Revised edition Edition


C. J. Parsloe

https://ebookname.com/product/water-distribution-systems-2nd-
revised-edition-edition-c-j-parsloe/
Operations Research 1st Edition R. Sivarethinamohan

https://ebookname.com/product/operations-research-1st-edition-r-
sivarethinamohan/
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 (http://my.safaribooksonline.com). For more information, contact our
corporate/institutional sales department: (800) 998-9938 or [email protected].

Editor: Julie Steele Indexer: John Bickelhaupt


Production Editor: Sumita Mukherji Cover Designer: Karen Montgomery
Copyeditor: Rachel Head Interior Designer: David Futato
Production Services: Newgen North America Illustrator: Robert Romano

Printing History:
March 1999: First Edition.
December 2003: Second Edition.
October 2007: Third Edition.
September 2009: 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 con-
tained 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? 3
Software Quality 4
Developer Productivity 5
Is Python a “Scripting Language”? 5
OK, but What’s the Downside? 7
Who Uses Python Today? 7
What Can I Do with Python? 9
Systems Programming 9
GUIs 9
Internet Scripting 10
Component Integration 10
Database Programming 11
Rapid Prototyping 11
Numeric and Scientific Programming 11
Gaming, Images, Serial Ports, XML, Robots, and More 12
How Is Python Supported? 12
What Are Python’s Technical Strengths? 13
It’s Object-Oriented 13
It’s Free 13
It’s Portable 14
It’s Powerful 15
It’s Mixable 16
It’s Easy to Use 16
It’s Easy to Learn 17
It’s Named After Monty Python 17
How Does Python Stack Up to Language X? 17

vii
Chapter Summary 18
Test Your Knowledge: Quiz 19
Test Your Knowledge: Answers 19

2. How Python Runs Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23


Introducing the Python Interpreter 23
Program Execution 24
The Programmer’s View 24
Python’s View 26
Execution Model Variations 29
Python Implementation Alternatives 29
Execution Optimization Tools 30
Frozen Binaries 32
Other Execution Options 33
Future Possibilities? 33
Chapter Summary 34
Test Your Knowledge: Quiz 34
Test Your Knowledge: Answers 34

3. How You Run Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


The Interactive Prompt 35
Running Code Interactively 37
Why the Interactive Prompt? 38
Using the Interactive Prompt 39
System Command Lines and Files 41
A First Script 42
Running Files with Command Lines 43
Using Command Lines and Files 44
Unix Executable Scripts (#!) 46
Clicking File Icons 47
Clicking Icons on Windows 47
The input Trick 49
Other Icon-Click Limitations 50
Module Imports and Reloads 51
The Grander Module Story: Attributes 53
import and reload Usage Notes 56
Using exec to Run Module Files 57
The IDLE User Interface 58
IDLE Basics 58
Using IDLE 60
Advanced IDLE Tools 62
Other IDEs 63
Other Launch Options 64

viii | Table of Contents


Embedding Calls 64
Frozen Binary Executables 65
Text Editor Launch Options 65
Still Other Launch Options 66
Future Possibilities? 66
Which Option Should I Use? 66
Chapter Summary 68
Test Your Knowledge: Quiz 68
Test Your Knowledge: Answers 69
Test Your Knowledge: Part I Exercises 70

Part II. Types and Operations

4. Introducing Python Object Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75


Why Use Built-in Types? 76
Python’s Core Data Types 77
Numbers 78
Strings 80
Sequence Operations 80
Immutability 82
Type-Specific Methods 82
Getting Help 84
Other Ways to Code Strings 85
Pattern Matching 85
Lists 86
Sequence Operations 86
Type-Specific Operations 87
Bounds Checking 87
Nesting 88
Comprehensions 88
Dictionaries 90
Mapping Operations 90
Nesting Revisited 91
Sorting Keys: for Loops 93
Iteration and Optimization 94
Missing Keys: if Tests 95
Tuples 96
Why Tuples? 97
Files 97
Other File-Like Tools 99
Other Core Types 99
How to Break Your Code’s Flexibility 100

Table of Contents | ix
User-Defined Classes 101
And Everything Else 102
Chapter Summary 103
Test Your Knowledge: Quiz 103
Test Your Knowledge: Answers 104

5. Numeric Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105


Numeric Type Basics 105
Numeric Literals 106
Built-in Numeric Tools 108
Python Expression Operators 108
Numbers in Action 113
Variables and Basic Expressions 113
Numeric Display Formats 115
Comparisons: Normal and Chained 116
Division: Classic, Floor, and True 117
Integer Precision 121
Complex Numbers 122
Hexadecimal, Octal, and Binary Notation 122
Bitwise Operations 124
Other Built-in Numeric Tools 125
Other Numeric Types 127
Decimal Type 127
Fraction Type 129
Sets 133
Booleans 139
Numeric Extensions 140
Chapter Summary 141
Test Your Knowledge: Quiz 141
Test Your Knowledge: Answers 141

6. The Dynamic Typing Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143


The Case of the Missing Declaration Statements 143
Variables, Objects, and References 144
Types Live with Objects, Not Variables 145
Objects Are Garbage-Collected 146
Shared References 148
Shared References and In-Place Changes 149
Shared References and Equality 151
Dynamic Typing Is Everywhere 152
Chapter Summary 153
Test Your Knowledge: Quiz 153
Test Your Knowledge: Answers 154

x | Table of Contents
7. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
String Literals 157
Single- and Double-Quoted Strings Are the Same 158
Escape Sequences Represent Special Bytes 158
Raw Strings Suppress Escapes 161
Triple Quotes Code Multiline Block Strings 162
Strings in Action 163
Basic Operations 164
Indexing and Slicing 165
String Conversion Tools 169
Changing Strings 171
String Methods 172
String Method Examples: Changing Strings 174
String Method Examples: Parsing Text 176
Other Common String Methods in Action 177
The Original string Module (Gone in 3.0) 178
String Formatting Expressions 179
Advanced String Formatting Expressions 181
Dictionary-Based String Formatting Expressions 182
String Formatting Method Calls 183
The Basics 184
Adding Keys, Attributes, and Offsets 184
Adding Specific Formatting 185
Comparison to the % Formatting Expression 187
Why the New Format Method? 190
General Type Categories 193
Types Share Operation Sets by Categories 194
Mutable Types Can Be Changed In-Place 194
Chapter Summary 195
Test Your Knowledge: Quiz 195
Test Your Knowledge: Answers 196

8. Lists and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197


Lists 197
Lists in Action 200
Basic List Operations 200
List Iteration and Comprehensions 200
Indexing, Slicing, and Matrixes 201
Changing Lists In-Place 202
Dictionaries 207
Dictionaries in Action 209
Basic Dictionary Operations 209
Changing Dictionaries In-Place 210

Table of Contents | xi
More Dictionary Methods 211
A Languages Table 212
Dictionary Usage Notes 213
Other Ways to Make Dictionaries 216
Dictionary Changes in Python 3.0 217
Chapter Summary 223
Test Your Knowledge: Quiz 224
Test Your Knowledge: Answers 224

9. Tuples, Files, and Everything Else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225


Tuples 225
Tuples in Action 227
Why Lists and Tuples? 229
Files 229
Opening Files 230
Using Files 231
Files in Action 232
Other File Tools 238
Type Categories Revisited 239
Object Flexibility 241
References Versus Copies 241
Comparisons, Equality, and Truth 244
Python 3.0 Dictionary Comparisons 246
The Meaning of True and False in Python 246
Python’s Type Hierarchies 248
Type Objects 249
Other Types in Python 250
Built-in Type Gotchas 251
Assignment Creates References, Not Copies 251
Repetition Adds One Level Deep 252
Beware of Cyclic Data Structures 252
Immutable Types Can’t Be Changed In-Place 253
Chapter Summary 253
Test Your Knowledge: Quiz 254
Test Your Knowledge: Answers 254
Test Your Knowledge: Part II Exercises 255

Part III. Statements and Syntax

10. Introducing Python Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261


Python Program Structure Revisited 261
Python’s Statements 262

xii | Table of Contents


A Tale of Two ifs 264
What Python Adds 264
What Python Removes 265
Why Indentation Syntax? 266
A Few Special Cases 269
A Quick Example: Interactive Loops 271
A Simple Interactive Loop 271
Doing Math on User Inputs 272
Handling Errors by Testing Inputs 273
Handling Errors with try Statements 274
Nesting Code Three Levels Deep 275
Chapter Summary 276
Test Your Knowledge: Quiz 276
Test Your Knowledge: Answers 277

11. Assignments, Expressions, and Prints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279


Assignment Statements 279
Assignment Statement Forms 280
Sequence Assignments 281
Extended Sequence Unpacking in Python 3.0 284
Multiple-Target Assignments 288
Augmented Assignments 289
Variable Name Rules 292
Expression Statements 295
Expression Statements and In-Place Changes 296
Print Operations 297
The Python 3.0 print Function 298
The Python 2.6 print Statement 300
Print Stream Redirection 302
Version-Neutral Printing 306
Chapter Summary 308
Test Your Knowledge: Quiz 308
Test Your Knowledge: Answers 308

12. if Tests and Syntax Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311


if Statements 311
General Format 311
Basic Examples 312
Multiway Branching 312
Python Syntax Rules 314
Block Delimiters: Indentation Rules 315
Statement Delimiters: Lines and Continuations 317
A Few Special Cases 318

Table of Contents | xiii


Truth Tests 320
The if/else Ternary Expression 321
Chapter Summary 324
Test Your Knowledge: Quiz 324
Test Your Knowledge: Answers 324

13. while and for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327


while Loops 327
General Format 328
Examples 328
break, continue, pass, and the Loop else 329
General Loop Format 329
pass 330
continue 331
break 331
Loop else 332
for Loops 334
General Format 334
Examples 335
Loop Coding Techniques 341
Counter Loops: while and range 342
Nonexhaustive Traversals: range and Slices 343
Changing Lists: range 344
Parallel Traversals: zip and map 345
Generating Both Offsets and Items: enumerate 348
Chapter Summary 349
Test Your Knowledge: Quiz 349
Test Your Knowledge: Answers 350

14. Iterations and Comprehensions, Part 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351


Iterators: A First Look 351
The Iteration Protocol: File Iterators 352
Manual Iteration: iter and next 354
Other Built-in Type Iterators 356
List Comprehensions: A First Look 358
List Comprehension Basics 359
Using List Comprehensions on Files 359
Extended List Comprehension Syntax 361
Other Iteration Contexts 362
New Iterables in Python 3.0 366
The range Iterator 367
The map, zip, and filter Iterators 368
Multiple Versus Single Iterators 369

xiv | Table of Contents


Dictionary View Iterators 370
Other Iterator Topics 372
Chapter Summary 372
Test Your Knowledge: Quiz 372
Test Your Knowledge: Answers 373

15. The Documentation Interlude . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375


Python Documentation Sources 375
# Comments 376
The dir Function 376
Docstrings: __doc__ 377
PyDoc: The help Function 380
PyDoc: HTML Reports 383
The Standard Manual Set 386
Web Resources 387
Published Books 387
Common Coding Gotchas 387
Chapter Summary 389
Test Your Knowledge: Quiz 389
Test Your Knowledge: Answers 390
Test Your Knowledge: Part III Exercises 390

Part IV. Functions

16. Function Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395


Why Use Functions? 396
Coding Functions 396
def Statements 398
def Executes at Runtime 399
A First Example: Definitions and Calls 400
Definition 400
Calls 400
Polymorphism in Python 401
A Second Example: Intersecting Sequences 402
Definition 402
Calls 403
Polymorphism Revisited 403
Local Variables 404
Chapter Summary 404
Test Your Knowledge: Quiz 405
Test Your Knowledge: Answers 405

Table of Contents | xv
17. Scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Python Scope Basics 407
Scope Rules 408
Name Resolution: The LEGB Rule 410
Scope Example 411
The Built-in Scope 412
The global Statement 414
Minimize Global Variables 415
Minimize Cross-File Changes 416
Other Ways to Access Globals 418
Scopes and Nested Functions 419
Nested Scope Details 419
Nested Scope Examples 419
The nonlocal Statement 425
nonlocal Basics 425
nonlocal in Action 426
Why nonlocal? 429
Chapter Summary 432
Test Your Knowledge: Quiz 433
Test Your Knowledge: Answers 434

18. Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435


Argument-Passing Basics 435
Arguments and Shared References 436
Avoiding Mutable Argument Changes 438
Simulating Output Parameters 439
Special Argument-Matching Modes 440
The Basics 441
Matching Syntax 442
The Gritty Details 443
Keyword and Default Examples 444
Arbitrary Arguments Examples 446
Python 3.0 Keyword-Only Arguments 450
The min Wakeup Call! 453
Full Credit 454
Bonus Points 455
The Punch Line... 456
Generalized Set Functions 456
Emulating the Python 3.0 print Function 457
Using Keyword-Only Arguments 459
Chapter Summary 460
Test Your Knowledge: Quiz 461
Test Your Knowledge: Answers 462

xvi | Table of Contents


19. Advanced Function Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
Function Design Concepts 463
Recursive Functions 465
Summation with Recursion 465
Coding Alternatives 466
Loop Statements Versus Recursion 467
Handling Arbitrary Structures 468
Function Objects: Attributes and Annotations 469
Indirect Function Calls 469
Function Introspection 470
Function Attributes 471
Function Annotations in 3.0 472
Anonymous Functions: lambda 474
lambda Basics 474
Why Use lambda? 475
How (Not) to Obfuscate Your Python Code 477
Nested lambdas and Scopes 478
Mapping Functions over Sequences: map 479
Functional Programming Tools: filter and reduce 481
Chapter Summary 483
Test Your Knowledge: Quiz 483
Test Your Knowledge: Answers 483

20. Iterations and Comprehensions, Part 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485


List Comprehensions Revisited: Functional Tools 485
List Comprehensions Versus map 486
Adding Tests and Nested Loops: filter 487
List Comprehensions and Matrixes 489
Comprehending List Comprehensions 490
Iterators Revisited: Generators 492
Generator Functions: yield Versus return 492
Generator Expressions: Iterators Meet Comprehensions 497
Generator Functions Versus Generator Expressions 498
Generators Are Single-Iterator Objects 499
Emulating zip and map with Iteration Tools 500
Value Generation in Built-in Types and Classes 506
3.0 Comprehension Syntax Summary 507
Comprehending Set and Dictionary Comprehensions 507
Extended Comprehension Syntax for Sets and Dictionaries 508
Timing Iteration Alternatives 509
Timing Module 509
Timing Script 510
Timing Results 511

Table of Contents | xvii


Timing Module Alternatives 513
Other Suggestions 517
Function Gotchas 518
Local Names Are Detected Statically 518
Defaults and Mutable Objects 520
Functions Without returns 522
Enclosing Scope Loop Variables 522
Chapter Summary 522
Test Your Knowledge: Quiz 523
Test Your Knowledge: Answers 523
Test Your Knowledge: Part IV Exercises 524

Part V. Modules

21. Modules: The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529


Why Use Modules? 529
Python Program Architecture 530
How to Structure a Program 531
Imports and Attributes 531
Standard Library Modules 533
How Imports Work 533
1. Find It 534
2. Compile It (Maybe) 534
3. Run It 535
The Module Search Path 535
Configuring the Search Path 537
Search Path Variations 538
The sys.path List 538
Module File Selection 539
Advanced Module Selection Concepts 540
Chapter Summary 541
Test Your Knowledge: Quiz 541
Test Your Knowledge: Answers 542

22. Module Coding Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543


Module Creation 543
Module Usage 544
The import Statement 544
The from Statement 545
The from * Statement 545
Imports Happen Only Once 546
import and from Are Assignments 546

xviii | Table of Contents


Cross-File Name Changes 547
import and from Equivalence 548
Potential Pitfalls of the from Statement 548
Module Namespaces 550
Files Generate Namespaces 550
Attribute Name Qualification 552
Imports Versus Scopes 552
Namespace Nesting 553
Reloading Modules 554
reload Basics 555
reload Example 556
Chapter Summary 558
Test Your Knowledge: Quiz 558
Test Your Knowledge: Answers 558

23. Module Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561


Package Import Basics 561
Packages and Search Path Settings 562
Package __init__.py Files 563
Package Import Example 564
from Versus import with Packages 566
Why Use Package Imports? 566
A Tale of Three Systems 567
Package Relative Imports 569
Changes in Python 3.0 570
Relative Import Basics 570
Why Relative Imports? 572
The Scope of Relative Imports 574
Module Lookup Rules Summary 575
Relative Imports in Action 575
Chapter Summary 581
Test Your Knowledge: Quiz 582
Test Your Knowledge: Answers 582

24. Advanced Module Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583


Data Hiding in Modules 583
Minimizing from * Damage: _X and __all__ 584
Enabling Future Language Features 584
Mixed Usage Modes: __name__ and __main__ 585
Unit Tests with __name__ 586
Using Command-Line Arguments with __name__ 587
Changing the Module Search Path 590
The as Extension for import and from 591

Table of Contents | xix


Modules Are Objects: Metaprograms 591
Importing Modules by Name String 594
Transitive Module Reloads 595
Module Design Concepts 598
Module Gotchas 599
Statement Order Matters in Top-Level Code 599
from Copies Names but Doesn’t Link 600
from * Can Obscure the Meaning of Variables 601
reload May Not Impact from Imports 601
reload, from, and Interactive Testing 602
Recursive from Imports May Not Work 603
Chapter Summary 604
Test Your Knowledge: Quiz 604
Test Your Knowledge: Answers 605
Test Your Knowledge: Part V Exercises 605

Part VI. Classes and OOP

25. OOP: The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611


Why Use Classes? 612
OOP from 30,000 Feet 613
Attribute Inheritance Search 613
Classes and Instances 615
Class Method Calls 616
Coding Class Trees 616
OOP Is About Code Reuse 619
Chapter Summary 622
Test Your Knowledge: Quiz 622
Test Your Knowledge: Answers 622

26. Class Coding Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625


Classes Generate Multiple Instance Objects 625
Class Objects Provide Default Behavior 626
Instance Objects Are Concrete Items 626
A First Example 627
Classes Are Customized by Inheritance 629
A Second Example 630
Classes Are Attributes in Modules 631
Classes Can Intercept Python Operators 633
A Third Example 634
Why Use Operator Overloading? 636
The World’s Simplest Python Class 636

xx | Table of Contents
Classes Versus Dictionaries 639
Chapter Summary 641
Test Your Knowledge: Quiz 641
Test Your Knowledge: Answers 641

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


Step 1: Making Instances 644
Coding Constructors 644
Testing As You Go 645
Using Code Two Ways 646
Step 2: Adding Behavior Methods 648
Coding Methods 649
Step 3: Operator Overloading 651
Providing Print Displays 652
Step 4: Customizing Behavior by Subclassing 653
Coding Subclasses 653
Augmenting Methods: The Bad Way 654
Augmenting Methods: The Good Way 654
Polymorphism in Action 656
Inherit, Customize, and Extend 657
OOP: The Big Idea 658
Step 5: Customizing Constructors, Too 658
OOP Is Simpler Than You May Think 660
Other Ways to Combine Classes 660
Step 6: Using Introspection Tools 663
Special Class Attributes 664
A Generic Display Tool 665
Instance Versus Class Attributes 666
Name Considerations in Tool Classes 667
Our Classes’ Final Form 668
Step 7 (Final): Storing Objects in a Database 669
Pickles and Shelves 670
Storing Objects on a Shelve Database 671
Exploring Shelves Interactively 672
Updating Objects on a Shelve 674
Future Directions 675
Chapter Summary 677
Test Your Knowledge: Quiz 677
Test Your Knowledge: Answers 678

28. Class Coding Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681


The class Statement 681
General Form 681

Table of Contents | xxi


Example 682
Methods 684
Method Example 685
Calling Superclass Constructors 686
Other Method Call Possibilities 686
Inheritance 687
Attribute Tree Construction 687
Specializing Inherited Methods 687
Class Interface Techniques 689
Abstract Superclasses 690
Python 2.6 and 3.0 Abstract Superclasses 692
Namespaces: The Whole Story 693
Simple Names: Global Unless Assigned 693
Attribute Names: Object Namespaces 693
The “Zen” of Python Namespaces: Assignments Classify Names 694
Namespace Dictionaries 696
Namespace Links 699
Documentation Strings Revisited 701
Classes Versus Modules 703
Chapter Summary 703
Test Your Knowledge: Quiz 703
Test Your Knowledge: Answers 704

29. Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705


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

xxii | Table of Contents


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

30. Designing with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737


Python and OOP 737
Overloading by Call Signatures (or Not) 738
OOP and Inheritance: “Is-a” Relationships 739
OOP and Composition: “Has-a” Relationships 740
Stream Processors Revisited 742
OOP and Delegation: “Wrapper” Objects 745
Pseudoprivate Class Attributes 747
Name Mangling Overview 748
Why Use Pseudoprivate Attributes? 748
Methods Are Objects: Bound or Unbound 750
Unbound Methods are Functions in 3.0 752
Bound Methods and Other Callable Objects 754
Multiple Inheritance: “Mix-in” Classes 756
Coding Mix-in Display Classes 757
Classes Are Objects: Generic Object Factories 768
Why Factories? 769
Other Design-Related Topics 770
Chapter Summary 770
Test Your Knowledge: Quiz 770
Test Your Knowledge: Answers 771

31. Advanced Class Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773


Extending Built-in Types 773
Extending Types by Embedding 774
Extending Types by Subclassing 775
The “New-Style” Class Model 777
New-Style Class Changes 778
Type Model Changes 779
Diamond Inheritance Change 783
New-Style Class Extensions 788
Instance Slots 788
Class Properties 792
__getattribute__ and Descriptors 794
Metaclasses 794
Static and Class Methods 795

Table of Contents | xxiii


Other documents randomly have
different content
I don't want to be anything else. But there are two sorts of power.
There's a power to do mischief—to undo what has been done with
great expense and labor, to waste and destroy, to be cruel to the
weak, to lie and quarrel, and to talk poisonous nonsense. That's the
sort of power that ignorant numbers have. It never made a joint
stool or planted a potato. Do you think it's likely to do much toward
governing a great country, and making wise laws, and giving shelter,
food, and clothes to millions of men? Ignorant power comes in the
end to the same thing as wicked power; it makes misery. It's
another sort of power that I want us workingmen to have, and I can
see plainly enough that our all having votes will do little toward it at
present. I hope we, or the children that come after us, will get
plenty of political power some time. I tell everybody plainly, I hope
there will be great changes, and that some time, whether we live to
see it or not, men will have come to be ashamed of things they're
proud of now. But I should like to convince you that votes would
never give you political power worth having while things are as they
are now, and that if you go the right way to work you may get
power sooner without votes. Perhaps all you who hear me are sober
men, who try to learn as much of the nature of things as you can,
and to be as little like fools as possible. A fool or idiot is one who
expects things to happen that never can happen; he pours milk into
a can without a bottom, and expects the milk to stay there. The
more of such vain expectations a man has, the more he is a fool or
idiot. And if any working man expects a vote to do for him what it
never can do, he's foolish to that amount, if no more. I think that's
clear enough, eh?"
"Hear, hear," said several voices, but they were not those of the
original group; they belonged to some strollers who had been
attracted by Felix Holt's vibrating voice, and were Tories from the
Crown. Among them was Christian, who was smoking a cigar with a
pleasure he always felt in being among people who did not know
him, and doubtless took him to be something higher than he really
was. Hearers from the Fox and Hounds also were slowly adding
themselves to the nucleus. Felix, accessible to the pleasure of being
listened to, went on with more and more animation: "The way to get
rid of folly is to get rid of vain expectations, and of thoughts that
don't agree with the nature of things. The men who have had true
thoughts about water, and what it will do when it is turned into
steam and under all sorts of circumstances, have made themselves a
great power in the world: they are turning the wheels of engines
that will help to change most things. But no engines would have
done, if there had been false notions about the way water would act.
Now, all the schemes about voting, and districts, and annual
Parliaments, and the rest, are engines, and the water or steam—the
force that is to work them—must come out of human nature—out of
men's passions, feelings, desires. Whether the engines will do good
work or bad depends on these feelings; and if we have false
expectations about men's characters, we are very much like the idiot
who thinks he'll carry milk in a can without a bottom. In my opinion,
the notions about what mere voting will do are very much of that
sort."
"That's very fine," said a man in dirty fustian, with a scornful
laugh. "But how are we to get the power without votes?"
"I'll tell you what's the greatest power under heaven," said Felix,
"and that is public opinion—the ruling belief in society about what is
right and what is wrong, what is honorable and what is shameful.
That's the steam that is to work the engines. How can political
freedom make us better, any more than a religion we don't believe
in, if people laugh and wink when they see men abuse and defile it?
And while public opinion is what it is—while men have no better
beliefs about public duty—while corruption is not felt to be a
damning disgrace—while men are not ashamed in Parliament and
out of it to make public questions which concern the welfare of
millions a mere screen for their own petty private ends,—I say, no
fresh scheme of voting will much mend our condition. For, take us
workingmen of all sorts. Suppose out of every hundred who had a
vote there were thirty who had some soberness, some sense to
choose with, some good feeling to make them wish the right thing
for all. And suppose there were seventy out of the hundred who
were, half of them, not sober, who had no sense to choose one thing
in politics more than another, and who had so little good feeling in
them that they wasted on their own drinking the money that should
have helped to feed and clothe their wives and children; and another
half of them who, if they didn't drink, were too ignorant or stupid to
see any good for themselves better than pocketing a five-shilling
piece when it was offered them. Where would be the political power
of the thirty sober men? The power would lie with the seventy
drunken and stupid votes; and I'll tell you what sort of men would
get the power—what sort of men would end by returning whom they
pleased to Parliament."
Felix had seen every face around him, and had particularly noticed
a recent addition to his audience; but now he looked about him,
without appearing to fix his glance on any one. In spite of his
cooling meditations an hour ago, his pulse was getting quickened by
indignation, and the desire to crush what he hated was likely to vent
itself in articulation. His tone became more biting.
"They would be men who would undertake to do the business for
a candidate, and return him: men who have no real opinions, but
who pilfer the words of every opinion, and turn them into a cant
which will serve their purpose at the moment; men who look out for
dirty work to make their fortunes by, because dirty work wants little
talent and no conscience; men who know all the ins and outs of
bribery, because there is not a cranny in their own souls where a
bribe can't enter. Such men as these will be the masters wherever
there's a majority of voters who care more for money, for drink,
more for some mean little end which is their own and nobody else's,
than for anything that has ever been called Right in the world. For
suppose there's a poor voter named Jack, who has seven children,
and twelve or fifteen shillings a-week wages, perhaps less. Jack can't
read—I don't say whose fault that is—he never had the chance to
learn; he knows so little that he perhaps thinks God made the poor-
laws, and if anybody said the pattern of the work-house was laid
down in the Testament, he wouldn't be able to contradict them.
What is poor Jack likely to do when he sees a smart stranger coming
to him, who happens to be just one of these men that I say will be
the masters till public opinion gets too hot for them? He's a middle-
sized man, we'll say; stout, with coat upon coat of fine broadcloth,
open enough to show a fine gold chain: none of your dark, scowling
men, but one with an innocent pink-and-white skin and very smooth
light hair—a most respectable man, who calls himself a good, sound,
well-known English name—as Green, or Baker, or Wilson, or let us
say, Johnson——"
Felix was interrupted by an explosion of laughter from a majority
of the bystanders. Some eyes had been turned on Johnson, who
stood on the right hand of Felix, at the very beginning of the
description, and these were gradually followed by others, till at last
every hearer's attention was fixed on him, and the first burst of
laughter from the two or three who knew the attorney's name, let
every one sufficiently into the secret to make the amusement
common. Johnson, who had kept his ground till his name was
mentioned, now turned away, looking unusually white after being
unusually red, and feeling by an attorney's instinct for his pocket-
book, as if he felt it was a case for taking down the names of
witnesses.
All the well-dressed hearers turned away too, thinking they had
had the cream of the speech in the joke against Johnson, which, as
a thing worth telling, helped to recall them to the scene of dinner.
"Who is this Johnson?" said Christian to a young man who had
been standing near him, and had been one of the first to laugh.
Christian's curiosity had naturally been awakened by what might
prove a golden opportunity.
"Oh—a London attorney. He acts for Transome. That tremendous
fellow at the corner there is some red-hot Radical demagogue, and
Johnson has offended him, I suppose; else he wouldn't have turned
in that way on a man of their own party."
"I had heard there was a Johnson who was an understrapper of
Jermyn's," said Christian.
"Well, so this man may have been for what I know. But he's a
London man now—a very busy fellow—on his own legs in Bedford
Row. Ha, ha! it's capital, though, when these Liberals get a slap in
the face from the workingmen they're so very fond of."
Another turn along the street enabled Christian to come to a
resolution. Having seen Jermyn drive away an hour before, he was
in no fear: he walked at once to the Fox and Hounds and asked to
speak to Mr. Johnson. A brief interview, in which Christian
ascertained that he had before him the Johnson mentioned by the
bill-sticker, issued in the appointment of a longer one at a later hour;
and before they left Duffield they had come not exactly to a mutual
understanding, but to an exchange of information mutually
welcome.
Christian had been very cautious in the commencement, only
intimating that he knew something important which some chance
hints had induced him to think might be interesting to Mr. Johnson,
but that this entirely depended on how far he had a common
interest with Mr. Jermyn. Johnson replied that he had much business
in which that gentleman was not concerned, but that to a certain
extent they had a common interest. Probably then, Christian
observed, the affairs of the Transome estate were part of the
business in which Mr. Jermyn and Mr. Johnson might be understood
to represent each other, in which case he need not detain Mr.
Johnson? At this hint Johnson could not conceal that he was
becoming eager. He had no idea what Christian's information was,
but there were many grounds on which Johnson desired to know as
much as he could about the Transome affairs independently of
Jermyn. By little and little an understanding was arrived at. Christian
told of his interview with Tommy Trounsem, and stated that if
Johnson could show him whether the knowledge could have any
legal value, he could bring evidence that a legitimate child of
Bycliffe's existed: he felt certain of his fact, and of his proof. Johnson
explained, that in this case the death of the old bill-sticker would
give the child the first valid claim to the Bycliffe heirship; that for his
own part he should be glad to further a true claim, but that caution
would have to be observed. How did Christian know that Jermyn,
was informed on this subject? Christian, more and more convinced
that Johnson would be glad to counteract Jermyn at length became
explicit about Esther, but still withheld his own real name, and the
nature of his relations with Bycliffe. He said he would bring the rest
of his information when Mr. Johnson took the case up seriously, and
place it in the hands of Bycliffe's old lawyers—of course he would do
that? Johnson replied that he would certainly do that; but that there
were legal niceties which Mr. Christian was probably not acquainted
with; that Esther's claim had not yet accrued, and that hurry was
useless.
The two men parted, each in distrust of the other, but each well
pleased to have learned something. Johnson was not at all sure how
he should act, but thought it likely that events would soon guide
him. Christian was beginning to meditate a way of securing his own
ends without depending in the least on Johnson's procedure. It was
enough for him that he was now assured of Esther's legal claim on
the Transome estates.
CHAPTER XXXI.

"In the copia of the factious language the word Tory was
entertained, and being a vocal clever-sounding word, readily
pronounced, it kept its hold, and took possession of the foul
mouths of the faction.——The Loyalists began to cheer up and
to take heart of grace, and in the working of this crisis,
according to the common law of scolding, they considered
which way to make payment for so much of Tory as they had
been treated with to clear scores.——Immediately the train
took, and ran like wildfire and became general. And so the
account of Tory was balanced, and soon began to run up a
sharp score on the other side."—North's Examen, p. 321.

At last the great epoch of the election for North Loamshire had
arrived. The roads approaching Treby were early traversed by a
larger number of vehicles, horsemen, and also foot-passengers than
were ever seen at the annual fair. Treby was the polling-place for
many voters whose faces were quite strange in the town; and if
there were some strangers who did not come to poll, though they
had business not unconnected with the election, they were not liable
to be regarded with suspicion or especial curiosity. It was
understood that no division of a county had ever been more
thoroughly canvassed, and that there would be a hard run between
Garstin and Transome. Mr. Johnson's headquarters were at Duffield;
but it was a maxim which he repeated after the great Putty, that a
capable agent makes himself omnipresent; and quite apart from the
express between him and Jermyn, Mr. John Johnson's presence in
the universe had potent effects on this December day at Treby
Magna.
A slight drizzling rain which was observed by some Tories who
looked out of their bedroom windows before six o'clock, made them
hope that, after all, the day might pass off better than alarmists had
expected. The rain was felt to be somehow on the side of quiet and
Conservatism; but soon the breaking of the clouds and the mild
gleams of a December sun brought back previous apprehensions. As
there were already precedents for riot at a Reformed election, and
as the Trebian district had had its confidence in the natural course of
things somewhat shaken by a landed proprietor with an old name
offering himself as a Radical candidate, the election had been looked
forward to by many with a vague sense that it would be an occasion
something like a fighting match, when bad characters would
probably assemble, and there might be struggles and alarms for
respectable men, which would make it expedient for them to take a
little neat brandy as a precaution beforehand and a restorative
afterward. The tenants on the Transome estate were comparatively
fearless: poor Mr. Goffe, of Rabbit's End, considered that "one thing
was as mauling as the other," and that an election was no worse
than the sheep-rot; while Mr. Dibbs, taking the more cheerful view of
a prosperous man, reflected that if the Radicals were dangerous, it
was safer to be on their side. It was the voters for Debarry and
Garstin who considered that they alone had the right to regard
themselves as targets for evil-minded men; and Mr. Crowder, if he
could have got his ideas countenanced, would have recommended a
muster of farm-servants with defensive pitchforks on the side of
Church and king. But the bolder men were rather gratified by the
prospect of being groaned at, so that they might face about and
groan in return.
Mr. Crow, the high constable of Treby, inwardly rehearsed a brief
address to a riotous crowd in case it should be wanted, having been
warned by the rector that it was a primary duty on these occasions
to keep a watch against provocation as well as violence. The rector,
with a brother magistrate who was on the spot, had thought it
desirable to swear in some special constables, but the presence of
loyal men not absolutely required for the polling was not looked at in
the light of a provocation. The Benefit Clubs from various quarters
made a show, some with the orange-colored ribbons and streamers
of the true Tory candidate, some with the mazarine of the Whig. The
orange-colored bands played "Auld Lang Syne," and a louder
mazarine band came across them with "Oh, whistle and I will come
to thee, my lad"—probably as the tune the most symbolical of
Liberalism which their repertory would furnish. There was not a
single club bearing the Radical blue: the Sproxton Club members
wore the mazarine, and Mr. Chubb wore so much of it that he looked
(at a sufficient distance) like a very large gentianella. It was
generally understood that "these brave fellows," representing the
fine institution of Benefit Clubs, holding aloft the motto, "Let
brotherly love continue," were a civil force calculated to encourage
voters of sound opinions and keep up their spirits. But a
considerable number of unadorned heavy navvies, colliers, and
stone-pit men, who used their freedom as British subjects to be
present in Treby on this great occasion, looked like a possible uncivil
force whose politics were dubious until it was clearly seen for whom
they cheered and for whom they groaned.
Thus the way up to the polling-booths was variously lined, and
those who walked it, to whatever side they belonged, had the
advantage of hearing from the opposite side what were the most
marked defects or excesses in their personal appearance; for the
Trebians of that day held, without being aware that they had Cicero's
authority for it, that the bodily blemishes of an opponent were a
legitimate ground for ridicule; but if the voter frustrated wit by being
handsome, he was groaned at and satirized according to a formula,
in which the adjective was Tory, Whig, or Radical, as the case might
be, and the substantive a blank to be filled up after the taste of the
speaker.
Some of the more timid had chosen to go through this ordeal as
early as possible in the morning. One of the earliest was Mr. Timothy
Rose, the gentleman-farmer from Leek Malton. He had left home
with some foreboding, having swathed his more vital parts in layers
of flannel, and put on two greatcoats as a soft kind of armor. But
reflecting with some trepidation that there were no resources for
protecting his head, he once more wavered in his intention to vote;
he once more observed to Mrs. Rose that these were hard times
when a man of independent property was expected to vote "willy-
nilly;" but finally coerced by the sense that he should be looked ill on
"in these times" if he did not stand by the gentlemen round about,
he set out in his gig, taking with him a powerful wagoner, whom he
ordered to keep him in sight as he went to the polling-booth. It was
hardly more than nine o'clock when Mr. Rose, having thus come up
to the level of his times, cheered himself with a little cherry-brandy
at the Marquis, drove away in a much more courageous spirit, and
got down at Mr. Nolan's, just outside the town. The retired Londoner,
he considered, was a man of experience, who would estimate
properly the judicious course he had taken, and could make it known
to others. Mr. Nolan was superintending the removal of some shrubs
in his garden.
"Well, Mr. Nolan," said Rose, twinkling a self-complacent look over
the red prominence of his cheeks, "have you been to give your vote
yet?"
"No; all in good time. I shall go presently."
"Well, I wouldn't lose an hour, I wouldn't. I said to myself, if I've
got to do gentlemen a favor, I'll do it at once. You see, I've got no
landlord, Nolan—I'm in that position o' life that I can be
independent."
"Just so, my dear sir," said the wiry-faced Nolan, pinching his
under-lip between his thumb and finger, and giving one of those
wonderful universal shrugs, by which he seemed to be recalling all
his garments from a tendency to disperse themselves. "Come in and
see Mrs. Nolan?"
"No, no, thankye. Mrs. Rose expects me back. But, as I was
saying, I'm a independent man, and I consider it's not my part to
show favor to one more than another, but to make things as even as
I can. If I'd been a tenant to anybody, well, in course I must have
voted for my landlord—that stands to sense. But I wish everybody
well; and if one's returned to Parliament more than another, nobody
can say it's my doing; for when you can vote for two, you can make
things even. So I gave one to Debarry and one to Transome; and I
wish Garstin no ill, but I can't help the odd number, and he hangs on
to Debarry, they say."
"God bless me, sir," said Mr. Nolan, coughing down a laugh, "don't
you perceive that you might as well have stayed at home and not
voted at all, unless you would rather send a Radical to Parliament
than a sober Whig?"
"Well, I'm sorry you should have anything to say against what I've
done, Nolan," said Mr. Rose, rather crestfallen, though sustained by
inward warmth. "I thought you'd agree with me, as you're a sensible
man. But the most a independent man can do is to try and please
all; and if he hasn't the luck—here's wishing I may do it another
time," added Mr. Rose, apparently confounding a toast with a
salutation, for he put out his hand for a passing shake, and then
stepped into his gig again.
At the time that Mr. Timothy Rose left the town, the crowd in King
Street and in the market-place, where the polling-booths stood, was
fluctuating. Voters as yet were scanty, and brave fellows who had
come from any distance this morning, or who had sat up late
drinking the night before, required some reinforcement of their
strength and spirits. Every public house in Treby, not excepting the
venerable and sombre Cross-Keys, was lively with changing and
numerous company. Not, of course, that there was any treating:
treating necessarily had stopped, from moral scruples, when once
"the writs were out;" but there was drinking, which did equally well
under any name.
Poor Tommy Trounsem, breakfasting here on Falstaff's proportion
of bread, and something which, for gentility's sake, I will call sack,
was more than usually victorious over the ills of life, and felt himself
one of the heroes of the day. He had an immense light-blue cockade
in his hat, and an amount of silver in a dirty little canvas bag which
astonished himself. For some reason, at first inscrutable to him, he
had been paid for his bill-sticking with great liberality at Mr. Jermyn's
office, in spite of his having been the victim of a trick by which he
had once lost his own bills and pasted up Debarry's; but he soon
saw that this was simply a recognition of his merit as "an old family
kept out of its rights," and also of his peculiar share in an occasion
when the family was to get into Parliament. Under these
circumstances, it was due from him that he should show himself
prominently where business was going forward, and give additional
value by his presence to every vote for Transome. With this view he
got a half-pint bottle filled with his peculiar kind of "sack," and
hastened back to the market-place, feeling good-natured and
patronizing toward all political parties, and only so far partial as his
family bound him to be.
But a disposition to concentrate at that extremity of King Street
which issued in the market-place, was not universal among the
increasing crowd. Some of them seemed attracted toward another
nucleus at the other extremity of King Street, near the Seven Stars.
This was Garstin's chief house, where his committee sat, and it was
also a point which must necessarily be passed by many voters
entering the town on the eastern side. It seemed natural that the
mazarine colors should be visible here, and that Pack, the tall
"shepherd" of the Sproxton men, should be seen moving to and fro
where there would be a frequent opportunity of cheering the voters
for a gentleman who had the chief share in the Sproxton mines. But
the side lanes and entries out of King Street were numerous enough
to relieve any pressure if there was need to make way. The lanes
had a distinguished reputation. Two of them had odors of brewing;
one had a side entrance to Mr. Tiliot's wine and spirit vaults; up
another Mr. Muscat's cheeses were frequently being unloaded; and
even some of the entries had those cheerful suggestions of plentiful
provision which were among the characteristics of Treby.
Between ten and eleven the voters came in more rapid
succession, and the whole scene became spirited. Cheers, sarcasms,
and oaths, which seemed to have a flavor of wit for many hearers,
were beginning to be reinforced by more practical demonstrations,
dubiously jocose. There was a disposition in the crowd to close and
hem in the way for voters, either going or coming, until they had
paid some kind of toll. It was difficult to see who set the example in
the transition from words to deeds. Some thought it was due to
Jacob Cuff, a Tory charity-man, who was a well-known ornament of
the pothouse, and gave his mind much leisure for amusing devices;
but questions of origination in stirring periods are notoriously hard to
settle. It is by no means necessary in human things that there
should be only one beginner. This, however, is certain—that Mr.
Chubb, who wished it to be noticed that he voted for Garstin solely,
was one of the first to get rather more notice than he wished, and
that he had his hat knocked off and crushed in the interest of
Debarry by Tories opposed to coalition. On the other hand, some
said it was at the same time that Mr. Pink, the saddler, being stopped
on his way and made to declare that he was going to vote for
Debarry, got himself well chalked as to his coat, and pushed up an
entry, where he remained the prisoner of terror combined with the
want of any back outlet, and never gave his vote that day.
The second Tory joke was performed with much gusto. The
majority of the Transome tenants came in a body from the Ram Inn,
with Mr. Banks, the bailiff, leading them. Poor Goffe was the last of
them, and his worn melancholy look and forward-leaning gait gave
the jocose Cuff the notion that the farmer was not what he called
"compus." Mr. Goffe was cut off from his companions and hemmed
in: asked, by voices with hot breath close to his ear, how many
horses he had, how many cows, how many fat pigs; then jostled
from one to another, who made trumpets with their hands, and
deafened him by telling him to vote for Debarry. In this way the
melancholy Goffe was hustled on till he was at the polling-booth,
filled with confused alarms, the immediate alarm being that of
having to go back in still worse fashion than he had come. Arriving
in this way after the other tenants had left, he astonished all hearers
who knew him for a tenant of the Transomes by saying "Debarry,"
and was jostled back trembling amid shouts of laughter.
By stages of this kind the fun grew faster, and was in danger of
getting rather serious. The Tories began to feel that their jokes were
returned by others of a heavier sort, and that the main strength of
the crowd was not on the side of sound opinion, but might come to
be on the side of sound cudgelling and kicking. The navvies and
pitmen in dishabille seemed to be multiplying, and to be clearly not
belonging to the party of Order. The shops were freely resorted to
for various forms of playful missiles and weapons; and news came to
the magistrates, watching from the large window of the Marquis,
that a gentleman coming in on horseback at the other end of the
street to vote for Garstin had had his horse turned round and
frightened into a headlong gallop out of it again.
Mr. Crow and his subordinates, and all the special constables, felt
that it was necessary to make some energetic effort, or else every
voter would be intimidated and the poll must be adjourned. The
rector determined to get on horseback and go amidst the crowd with
the constables; and he sent a message to Mr. Lingon, who was at
the Ram, calling on him to do the same. "Sporting Jack" was sure
the good fellows meant no harm, but he was courageous enough to
face any bodily dangers, and rode out in his brown leggings and
colored bandana, speaking persuasively.
It was nearly twelve o'clock when this sally was made: the
constables and magistrates tried the most pacific measures, and
they seemed to succeed. There was a rapid thinning of the crowd:
the most boisterous disappeared, or seemed to do so by becoming
quiet; missiles ceased to fly, and a sufficient way was cleared for
voters along King Street. The magistrates returned to their quarters,
and the constables took convenient posts of observation. Mr. Wace,
who was one of Debarry's committee, had suggested to the rector
that it might be wise to send for the military from Duffield, with
orders that they should station themselves at Hathercote, three
miles off: there was so much property in the town that it would be
better to make it secure against risks. But the rector felt that this
was not the part of a moderate and wise magistrate, unless the
signs of riot recurred. He was a brave man, and fond of thinking that
his own authority sufficed for the maintenance of the general good
in Treby.
CHAPTER XXXII.

Go from me. Yet I feel that I shall stand


Henceforward in thy shadow. Nevermore
Alone upon the threshold of my door
Of individual life, I shall command
The uses of my soul, nor lift my hand
Serenely in the sunshine as before
Without the sense of that which I forbore—
Thy touch upon the palm. The widest land
Doom takes to part us, leaves thy heart in mine
With pulses that beat double. What I do
And what I dream include thee, as the wine
Must taste of its own grapes. And when I sue
God for myself, He hears that name of thine,
And sees within my eyes the tears of two.

—Mrs. Browning.

Felix Holt, seated at his work without his pupils, who had asked
for a holiday with a notion that the wooden booths promised some
sort of show, noticed about eleven o'clock that the noises which
reached him from the main street were getting more and more
tumultuous. He had long seen bad auguries for this election, but,
like all people who dread the prophetic wisdom that ends in desiring
the fulfillment of its own evil forebodings, he had checked himself
with remembering that, though many conditions were possible which
might bring on violence, there were just as many which might avert
it. There would, perhaps, be no other mischief than what he was
already certain of. With these thoughts he sat down quietly to his
work, meaning not to vex his soul by going to look on at things he
would fain have made different if he could. But he was of a fiber that
vibrated too strongly to the life around him to shut himself away in
quiet, even from suffering and irremediable wrong. As the noises
grew louder, and wrought more and more strongly on his
imagination, he was obliged to lay down his delicate wheel-work. His
mother came from her turnip-paring, in the kitchen, where little Job
was her companion, to observe that they must be killing everybody
in the High Street, and that the election, which had never been
before at Treby, must have come for a judgment; that there were
mercies where you didn't look for them, and that she thanked God in
His wisdom for making her live up a back street.
Felix snatched his cap and rushed out. But when he got to the
turning into the market-place the magistrates were already on
horseback there, the constables were moving about, and Felix
observed that there was no strong spirit of resistance to them. He
stayed long enough to see the partial dispersion of the crowd and
the restoration of tolerable quiet, and then went back to Mrs. Holt to
tell her that there was nothing to fear now; he was going out again,
and she must not be in any anxiety at his absence. She might set by
his dinner for him.
Felix had been thinking of Esther and her probable alarm at the
noises that must have reached her more distinctly than they had
reached him, for Malthouse Yard was removed but a little way from
the main street. Mr. Lyon was away from home, having been called
to preach charity sermons and attend meetings in a distant town;
and Esther, with the plaintive Lyddy for her sole companion, was not
cheerfully circumstanced. Felix had not been to see her yet since her
father's departure, but to-day he gave way to new reasons.
"Miss Esther was in the garret," Lyddy said, trying to see what was
going on. But before she was fetched she came running down the
stairs, drawn by the knock at the door, which had shaken the small
dwelling.
"I am so thankful to see you," she said, eagerly. "Pray come in."
When she had shut the parlor door behind them, Felix said, "I
suspected that you might have been made anxious by the noises. I
came to tell you that things are quiet now. Though, indeed, you can
hear that they are."
"I was frightened," said Esther. "The shouting and roaring of rude
men is so hideous. It is a relief to me that my father is not at home
—that he is out of the reach of any danger he might have fallen into
if he had been here. But I gave you credit for being in the midst of
the danger," she added, smiling, with a determination not to show
much feeling. "Sit down and tell me what has happened."
They sat down at the extremities of the old black sofa, and Felix
said—
"To tell you the truth, I had shut myself up, and tried to be as
indifferent to the election as if I'd been one of the fishes in the Lapp,
till the noises got too strong for me. But I only saw the tail end of
the disturbance. The poor noisy simpletons seemed to give way
before the magistrates and the constables. I hope nobody has been
much hurt. The fear is that they may turn out again by-and-by; their
giving way so soon may not be altogether a good sign. There's a
great number of heavy fellows in the town. If they go and drink
more, the last end may be worse than the first. However——"
Felix broke off, as if this talk was futile, clasped his hands behind
his head, and, leaning backward, looked at Esther, who was looking
at him.
"May I stay here a little while?" he said, after a moment, which
seemed long.
"Pray do," said Esther, coloring. To relieve herself she took some
work and bowed her head over her stitching. It was in reality a little
heaven to her that Felix was there, but she saw beyond it—saw that
by-and-by he would be gone, and that they should be farther on
their way, not toward meeting, but parting. His will was
impregnable. He was a rock, and she was no more to him than the
white clinging mist-cloud.
"I wish I could be sure that you see things just as I do," he said
abruptly, after a minute's silence.
"I am sure you see them much more wisely than I do!" said
Esther, almost bitterly, without looking up.
"There are some people one must wish to judge truly. Not to wish
it would be mere hardness. I know you think I am a man without
feeling—at least, without strong affections. You think I love nothing
but my own resolutions."
"Suppose I reply in the same sort of strain?" said Esther, with a
little toss of the head.
"How?"
"Why, that you think me a shallow woman, incapable of believing
what is best in you, setting down everything that is too high for me
as a deficiency."
"Don't parry what I say. Answer me." There was an expression of
painful beseeching in the tone with which Felix said this. Esther let
her work fall on her lap and looked at him, but she was unable to
speak.
"I want you to tell me—once—that you know it would be easier to
me to give myself up to loving and being loved, as other men do,
when they can, than to——"
This breaking-off in speech was something quite new in Felix. For
the first time he had lost his self-possession, and turned his eyes
away. He was at variance with himself. He had begun what he felt he
ought not to finish.
Esther, like a woman as she was—a woman waiting for love, never
able to ask for it—had her joy in these signs of her power; but they
made her generous, not chary, as they might have done if she had
had a pettier disposition. She said, with deep yet timid earnestness—
"What you have chosen to do has only convinced me that your
love would be the better worth having."
All the finest part of Esther's nature trembled in those words. To
be right in great memorable moments is perhaps the thing we need
most desire for ourselves.
Felix as quick as lightning turned his look upon her again, and,
leaning forward, took her sweet hand and held it to his lips some
moments before he let it fall again and raised his head.
"We shall always be the better for thinking of each other," he said,
leaning his elbow on the back of the sofa, and supporting his head
as he looked at her with calm sadness. "This thing can never come
to me twice over. It is my knighthood. That was always a business of
great cost."
He smiled at her, but she sat biting her inner lip and pressing her
hands together. She desired to be worthy of what she reverenced in
Felix, but the inevitable renunciation was too difficult. She saw
herself wandering through the future weak and forsaken. The
charming sauciness was all gone from her face, but the memory of it
made this childlike dependent sorrow all the more touching.
"Tell me what you would——" Felix burst out, leaning nearer to
her; but the next instant he started up, went to the table, took his
cap in his hand and came in front of her.
"Good-bye," he said, very gently, not daring to put out his hand.
But Esther put up hers instead of speaking. He just pressed it and
then went away.
She heard the doors close behind him, and felt free to be
miserable. She cried bitterly. If she might have married Felix Holt,
she could have been a good woman. She felt no trust that she could
ever be good without him.
Felix reproached himself. He would have done better not to speak
in that way. But the prompting to which he had chiefly listened had
been the desire to prove to Esther that he set a high value on her
feelings. He could not help seeing that he was very important to her;
and he was too simple and sincere a man to ape a sort of humility
which would not have made him any the better if he had possessed
it. Such pretences turn our lives into sorry dramas. And Felix wished
Esther to know that her love was dear to him as the beloved dead
are dear. He felt that they must not marry—that they would ruin
each other's lives. But he had longed for her to know fully that his
will to be always apart from her was renunciation, not an easy
preference. In this he was thoroughly generous; and yet, now some
subtle, mysterious conjuncture of impressions and circumstances
had made him speak, he questioned the wisdom of what he had
done. Express confessions give definiteness to memories that might
more easily melt away without; and Felix felt for Esther's pain as the
strong soldier, who can march on hungering without fear that he
shall faint, feels for the young brother—the maiden-cheeked
conscript whose load is too heavy for him.
CHAPTER XXXIII.

Mischief, thou art afoot.—Julius Cæsar.


Felix could not go home again immediately after quitting Esther.
He got out of the town, skirted it a little while, looking across the
December stillness of the fields, and then re-entered it by the main
road into the market-place, thinking that, after all, it would be better
for him to look at the busy doings of men than to listen in solitude to
the voices within him; and he wished to know how things were
going on.
It was now nearly half-past one, and Felix perceived that the
street was filling with more than the previous crowd. By the time he
got in front of the booths, he was himself so surrounded by men
who were being thrust hither and thither that retreat would have
been impossible; and he went where he was obliged to go, although
his height and strength were above the average even in a crowd
where there were so many heavy-armed workmen used to the
pickaxe. Almost all shabby-coated Trebians must have been there,
but the entries and back streets of the town did not supply the mass
of the crowd; and besides the rural incomers, both of the more
decent and the rougher sort, Felix, as he was pushed along, thought
he discerned here and there men of that keener aspect which is only
common in manufacturing towns.
But at present there was no evidence of any distinctly mischievous
design. There was only evidence that the majority of the crowd were
excited with drink, and that their action could hardly be calculated
on more than those of the oxen and pigs congregated amidst
hootings and pushings. The confused deafening shouts, the
incidental fighting, the knocking over, pulling and scuffling, seemed
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like