Objectoriented Python 1st Edition Irv Kalb
download
https://ebookbell.com/product/objectoriented-python-1st-edition-
irv-kalb-42304954
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Objectoriented Python 1st Edition Irv Kalb
https://ebookbell.com/product/objectoriented-python-1st-edition-irv-
kalb-36397474
Objectoriented Python 1 Converted Irv Kalb
https://ebookbell.com/product/objectoriented-python-1-converted-irv-
kalb-36430034
Objectoriented Python Master Oop Through Game Development And Gui
Applications Kameron Hussain Frahaan Hussain
https://ebookbell.com/product/objectoriented-python-master-oop-
through-game-development-and-gui-applications-kameron-hussain-frahaan-
hussain-79088142
Objectoriented Python Irv Kalb
https://ebookbell.com/product/objectoriented-python-irv-kalb-42302770
Objectoriented Python Irv Kalb
https://ebookbell.com/product/objectoriented-python-irv-kalb-42322876
Objectoriented Python Irv Kalb
https://ebookbell.com/product/objectoriented-python-irv-kalb-42302434
An Object Oriented Python Cookbook In Quantum Information Theory And
Quantum Computing M S Ramkarthik
https://ebookbell.com/product/an-object-oriented-python-cookbook-in-
quantum-information-theory-and-quantum-computing-m-s-
ramkarthik-46375732
Mastering Objectoriented Python Steven F Lott
https://ebookbell.com/product/mastering-objectoriented-python-steven-
f-lott-4706056
Mastering Objectoriented Python 2nd Edition 2nd Edition Steven F Lott
https://ebookbell.com/product/mastering-objectoriented-python-2nd-
edition-2nd-edition-steven-f-lott-10469262
Objectoriented Python 1st Edition Irv Kalb
Objectoriented Python 1st Edition Irv Kalb
CONTENTS IN DETAIL
TITLE PAGE
COPYRIGHT
DEDICATION
ABOUT THE AUTHOR
ACKNOWLEDGMENTS
INTRODUCTION
Who Is This Book For?
Python Version(s) and Installation
How Will I Explain OOP?
What’s in the Book
Development Environments
Widgets and Example Games
PART I: INTRODUCING OBJECT-ORIENTED
PROGRAMMING
CHAPTER 1: PROCEDURAL PYTHON EXAMPLES
Higher or Lower Card Game
Representing the Data
Implementation
Reusable Code
Bank Account Simulations
Analysis of Required Operations and Data
Implementation 1—Single Account Without Functions
Implementation 2—Single Account with Functions
Implementation 3—Two Accounts
Implementation 4—Multiple Accounts Using Lists
Implementation 5—List of Account Dictionaries
Common Problems with Procedural Implementation
Object-Oriented Solution—First Look at a Class
Summary
CHAPTER 2: MODELING PHYSICAL OBJECTS WITH OBJECT-
ORIENTED PROGRAMMING
Building Software Models of Physical Objects
State and Behavior: Light Switch Example
Classes, Objects, and Instantiation
Writing a Class in Python
Scope and Instance Variables
Differences Between Functions and Methods
Creating an Object from a Class
Calling Methods of an Object
Creating Multiple Instances from the Same Class
Python Data Types Are Implemented as Classes
Definition of an Object
Building a Slightly More Complicated Class
Representing a More Complicated Physical Object as a Class
Passing Arguments to a Method
Multiple Instances
Initialization Parameters
Classes in Use
OOP as a Solution
Summary
CHAPTER 3: MENTAL MODELS OF OBJECTS AND THE
MEANING OF “SELF”
Revisiting the DimmerSwitch Class
High-Level Mental Model #1
A Deeper Mental Model #2
What Is the Meaning of “self”?
Summary
CHAPTER 4: MANAGING MULTIPLE OBJECTS
Bank Account Class
Importing Class Code
Creating Some Test Code
Creating Multiple Accounts
Multiple Account Objects in a List
Multiple Objects with Unique Identifiers
Building an Interactive Menu
Creating an Object Manager Object
Building the Object Manager Object
Main Code That Creates an Object Manager Object
Better Error Handling with Exceptions
try and except
The raise Statement and Custom Exceptions
Using Exceptions in Our Bank Program
Account Class with Exceptions
Optimized Bank Class
Main Code That Handles Exceptions
Calling the Same Method on a List of Objects
Interface vs. Implementation
Summary
PART II: GRAPHICAL USER INTERFACES WITH
PYGAME
CHAPTER 5: INTRODUCTION TO PYGAME
Installing Pygame
Window Details
The Window Coordinate System
Pixel Colors
Event-Driven Programs
Using Pygame
Bringing Up a Blank Window
Drawing an Image
Detecting a Mouse Click
Handling the Keyboard
Creating a Location-Based Animation
Using Pygame rects
Playing Sounds
Playing Sound Effects
Playing Background Music
Drawing Shapes
Reference for Primitive Shapes
Summary
CHAPTER 6: OBJECT-ORIENTED PYGAME
Building the Screensaver Ball with OOP Pygame
Creating a Ball Class
Using the Ball Class
Creating Many Ball Objects
Creating Many, Many Ball Objects
Building a Reusable Object-Oriented Button
Building a Button Class
Main Code Using a SimpleButton
Creating a Program with Multiple Buttons
Building a Reusable Object-Oriented Text Display
Steps to Display Text
Creating a SimpleText Class
Demo Ball with SimpleText and SimpleButton
Interface vs. Implementation
Callbacks
Creating a Callback
Using a Callback with SimpleButton
Summary
CHAPTER 7: PYGAME GUI WIDGETS
Passing Arguments into a Function or Method
Positional and Keyword Parameters
Additional Notes on Keyword Parameters
Using None as a Default Value
Choosing Keywords and Default Values
Default Values in GUI Widgets
The pygwidgets Package
Setting Up
Overall Design Approach
Adding an Image
Adding Buttons, Checkboxes, and Radio Buttons
Text Output and Input
Other pygwidgets Classes
pygwidgets Example Program
The Importance of a Consistent API
Summary
PART III: ENCAPSULATION, POLYMORPHISM, AND
INHERITANCE
CHAPTER 8: ENCAPSULATION
Encapsulation with Functions
Encapsulation with Objects
Objects Own Their Data
Interpretations of Encapsulation
Direct Access and Why You Should Avoid It
Strict Interpretation with Getters and Setters
Safe Direct Access
Making Instance Variables More Private
Implicitly Private
More Explicitly Private
Decorators and @property
Encapsulation in pygwidgets Classes
A Story from the Real World
Abstraction
Summary
CHAPTER 9: POLYMORPHISM
Sending Messages to Real-World Objects
A Classic Example of Polymorphism in Programming
Example Using Pygame Shapes
The Square Shape Class
The Circle and Triangle Shape Classes
The Main Program Creating Shapes
Extending a Pattern
pygwidgets Exhibits Polymorphism
Polymorphism for Operators
Magic Methods
Comparison Operator Magic Methods
A Rectangle Class with Magic Methods
Main Program Using Magic Methods
Math Operator Magic Methods
Vector Example
Creating a String Representation of Values in an Object
A Fraction Class with Magic Methods
Summary
CHAPTER 10: INHERITANCE
Inheritance in Object-Oriented Programming
Implementing Inheritance
Employee and Manager Example
Base Class: Employee
Subclass: Manager
Test Code
The Client’s View of a Subclass
Real-World Examples of Inheritance
InputNumber
DisplayMoney
Example Usage
Multiple Classes Inheriting from the Same Base Class
Abstract Classes and Methods
How pygwidgets Uses Inheritance
Class Hierarchy
The Difficulty of Programming with Inheritance
Summary
CHAPTER 11: MANAGING MEMORY USED BY OBJECTS
Object Lifetime
Reference Count
Garbage Collection
Class Variables
Class Variable Constants
Class Variables for Counting
Putting It All Together: Balloon Sample Program
Module of Constants
Main Program Code
Balloon Manager
Balloon Class and Objects
Managing Memory: Slots
Summary
PART IV: USING OOP IN GAME DEVELOPMENT
CHAPTER 12: CARD GAMES
The Card Class
The Deck Class
The Higher or Lower Game
Main Program
Game Object
Testing with __name__
Other Card Games
Blackjack Deck
Games with Unusual Card Decks
Summary
CHAPTER 13: TIMERS
Timer Demonstration Program
Three Approaches for Implementing Timers
Counting Frames
Timer Event
Building a Timer by Calculating Elapsed Time
Installing pyghelpers
The Timer Class
Displaying Time
CountUpTimer
CountDownTimer
Summary
CHAPTER 14: ANIMATION
Building Animation Classes
SimpleAnimation Class
SimpleSpriteSheetAnimation Class
Merging Two Classes
Animation Classes in pygwidgets
Animation Class
SpriteSheetAnimation Class
Common Base Class: PygAnimation
Example Animation Program
Summary
CHAPTER 15: SCENES
The State Machine Approach
A pygame Example with a State Machine
A Scene Manager for Managing Many Scenes
A Demo Program Using a Scene Manager
The Main Program
Building the Scenes
A Typical Scene
Rock, Paper, Scissors Using Scenes
Communication Between Scenes
Requesting Information from a Target Scene
Sending Information to a Target Scene
Sending Information to All Scenes
Testing Communications Among Scenes
Implementation of the Scene Manager
run() Method
Main Methods
Communication Between Scenes
Summary
CHAPTER 16: FULL GAME: DODGER
Modal Dialogs
Yes/No and Alert Dialogs
Answer Dialogs
Building a Full Game: Dodger
Game Overview
Implementation
Extensions to the Game
Summary
CHAPTER 17: DESIGN PATTERNS AND WRAP-UP
Model View Controller
File Display Example
Statistical Display Example
Advantages of the MVC Pattern
Wrap-Up
INDEX
OBJECT-ORIENTED PYTHON
Master OOP by Building Games and
GUIs
by Irv Kalb
Object-Oriented Python. Copyright © 2022 by Irv Kalb.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by
any means, electronic or mechanical, including photocopying, recording, or by any
information storage or retrieval system, without the prior written permission of the copyright
owner and the publisher.
First printing
25 24 23 22 21 1 2 3 4 5 6 7 8 9
ISBN-13: 978-1-7185-0206-2 (print)
ISBN-13: 978-1-7185-0207-9 (ebook)
Publisher: William Pollock
Managing Editor: Jill Franklin
Production Manager: Rachel Monaghan
Production Editor: Kate Kaminski
Developmental Editor: Liz Chadwick
Cover Illustrator: James L. Barry
Interior Design: Octopod Studios
Technical Reviewer: Monte Davidoff
Copyeditor: Rachel Head
Compositor: Maureen Forys, Happenstance Type-O-Rama
Proofreader: Paula L. Fleming
Indexer: Valerie Haynes Perry
The following images are reproduced with permission:
Figure 2-1, photo by David Benbennick, printed under the Creative Commons Attribution-
Share Alike 3.0 Unported license, https://creativecommons.org/licenses/by-sa/3.0/deed.en.
For information on book distributors or translations, please contact No Starch Press, Inc.
directly:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900; info@nostarch.com
www.nostarch.com
Library of Congress Cataloging-in-Publication Data
Names: Kalb, Irv, author.
Title: Object-oriented Python: master OOP by building games and GUIs / Irv Kalb.
Description: San Francisco : No Starch Press, [2021] | Includes index. |
Identifiers: LCCN 2021044174 (print) | LCCN 2021044175 (ebook) | ISBN
9781718502062 (print) | ISBN 9781718502079 (ebook)
Subjects: LCSH: Object-oriented programming (Computer science) | Python
(Computer program language)
Classification: LCC QA76.64 .K3563 2021 (print) | LCC QA76.64 (ebook) |
DDC 005.1/17--dc23
LC record available at https://lccn.loc.gov/2021044174
LC ebook record available at https://lccn.loc.gov/2021044175
No Starch Press and the No Starch Press logo are registered trademarks of No Starch
Press, Inc. Other product and company names mentioned herein may be the trademarks of
their respective owners. Rather than use a trademark symbol with every occurrence of a
trademarked name, we are using the names only in an editorial fashion and to the benefit of
the trademark owner, with no intention of infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty. While every
precaution has been taken in the preparation of this work, neither the author nor No Starch
Press, Inc. shall have any liability to any person or entity with respect to any loss or damage
caused or alleged to be caused directly or indirectly by the information contained in it.
To my
wonderful
wife,
Doreen.
You are
the glue
that keeps
our family
together.
Many
years ago,
I said, “I
do,” but
what I
meant
was, “I
will.”
About the Author
Irv Kalb is an adjunct professor at UCSC Silicon Valley Extension
and the University of Silicon Valley (formerly Cogswell Polytechnical
College), where he teaches introductory and object-oriented
programming courses in Python. Irv has a bachelor’s and a master’s
degree in computer science, has been using object-oriented
programming for over 30 years in a number of different computer
languages, and has been teaching for over 10 years. He has
decades of experience developing software, with a focus on
educational software. As Furry Pants Productions, he and his wife
created and shipped two edutainment CD-ROMs based on the
character Darby the Dalmatian. Irv is also the author of Learn to
Program with Python 3: A Step-by-Step Guide to Programming
(Apress).
Irv was heavily involved in the early development of the sport of
Ultimate Frisbee®. He led the effort of writing many versions of the
official rule book and co-authored and self-published the first book
on the sport, Ultimate: Fundamentals of the Sport.
About the Technical Reviewer
Monte Davidoff is an independent software development consultant.
His areas of expertise include DevOps and Linux. Monte has been
programming in Python for over 20 years. He has used Python to
develop a variety of software, including business-critical applications
and embedded software.
ACKNOWLEDGMENTS
I would like to thank the following people, who helped make this
book possible:
Al Sweigart, for getting me started in the use of pygame (especially
with his “Pygbutton” code) and for allowing me to use the concept of
his “Dodger” game.
Monte Davidoff, who was instrumental in helping me get the source
code and documentation of that code to build correctly through the
use of GitHub, Sphinx, and ReadTheDocs. He worked miracles
using a myriad of tools to wrestle the appropriate files into
submission.
Monte Davidoff (yes, the same guy), for being an outstanding
technical reviewer. Monte made excellent technical and writing
suggestions throughout the book, and many of the code examples
are more Pythonic and more OOP-ish because of his comments.
Tep Sathya Khieu, who did a stellar job of drawing all the original
diagrams for this book. I am not an artist (I don’t even play one on
TV). Tep was able to take my primitive pencil sketches and turn them
into clear, consistent pieces of art.
Harrison Yung, Kevin Ly, and Emily Allis, for their contributions of
artwork in some of the game art.
The early reviewers, Illya Katsyuk, Jamie Kalb, Gergana Angelova,
and Joe Langmuir, who found and corrected many typos and made
excellent suggestions for modifications and clarifications.
All the editors who worked on this book: Liz Chadwick
(developmental editor), Rachel Head (copyeditor), and Kate
Kaminski (production editor). They all made huge contributions by
questioning and often rewording and reorganizing some of my
explanations of concepts. They were also extremely helpful in adding
and removing commas [do I need one here?] and lengthening my
sentences as I am doing here to make sure that the point comes
across cleanly (OK, I’ll stop!). I’m afraid that I’ll never understand
when to use “which” versus “that,” or when to use a comma and
when to use a dash, but I’m glad that they know! Thanks also to
Maureen Forys (compositor) for her valuable contributions to the
finished product.
All the students who have been in my classes over the years at the
UCSC Silicon Valley Extension and at the University of Silicon Valley
(formerly Cogswell Polytechnical College). Their feedback,
suggestions, smiles, frowns, light-bulb moments, frustrations,
knowing head nods, and even thumbs-up (in Zoom classes during
the COVID era) were extremely helpful in shaping the content of this
book and my overall teaching style.
Finally, my family, who supported me through the long process of
writing, testing, editing, rewriting, editing, debugging, editing,
rewriting, editing (and so on) this book and the associated code. I
couldn’t have done it without them. I wasn’t sure if we had enough
books in our library, so I wrote another one!
INTRODUCTION
This book is about a software
development technique called
object-oriented programming (OOP)
and how it can be used with Python.
Before OOP, programmers used an
approach known as procedural programming,
also called structured programming, which
involves building a set of functions (procedures)
and passing data around through calls to those
functions. The OOP paradigm gives
programmers an efficient way to combine code
and data into cohesive units that are often highly
reusable.
In preparation for writing this book, I extensively researched
existing literature and videos, looking specifically at the approaches
taken to explain this important and wide-ranging topic. I found that
instructors and writers typically start by defining certain key terms:
class, instance variable, method, encapsulation, inheritance,
polymorphism, and so on.
While these are all important concepts, and I’ll cover all of them in
depth in this book, I’ll begin in a different way: by considering the
question, “What problem are we solving?” That is, if OOP is the
solution, then what is the problem? To answer this question, I’ll start
by presenting a few examples of programs built using procedural
programming and identifying complications inherent in this style.
Then I’ll show you how an object-oriented approach can make the
construction of such programs much easier and the programs
themselves more maintainable.
Who Is This Book For?
This book is intended for people who already have some familiarity
with Python and with using basic functions from the Python Standard
Library. I will assume that you understand the fundamental syntax of
the language and can write small- to medium-sized programs using
variables, assignment statements, if/elif/else statements, while
and for loops, functions and function calls, lists, dictionaries, and so
on. If you aren’t comfortable with all of these concepts, then I
suggest that you get a copy of my earlier book, Learn to Program
with Python 3 (Apress), and read that first.
This is an intermediate-level text, so there are a number of more
advanced topics that I will not address. For example, to keep the
book practical, I will not often go into detail on the internal
implementation of Python. For simplicity and clarity, and to keep the
focus on mastering OOP techniques, the examples are written using
a limited subset of the language. There are more advanced and
concise ways to code in Python that are beyond the scope of this
book.
I will cover the underlying details of OOP in a mostly language-
independent way, but will point out areas where there are differences
between Python and other OOP languages. Having learned the
basics of OOP-style coding through this book, if you wish, you
should be able to easily apply these techniques to other OOP
languages.
Python Version(s) and Installation
All the example code in this book was written and tested using
Python versions 3.6 through 3.9. All the examples should work fine
with version 3.6 or newer.
Python is available for free at https://www.python.org. If you don’t
have Python installed, or you want to upgrade to the latest version,
go to that site, find the Downloads tab, and click the Download
button. This will download an installable file onto your computer.
Double-click the file that was downloaded to install Python.
WINDOWS INSTALLATION
If you’re installing on a Windows system, there is one important option that you need to
set correctly. When running through the installation steps, you should see a screen like
this:
At the bottom of the dialog is a checkbox labeled “Add Python 3.x to PATH.” Please be
sure to check this box (it defaults to unchecked). This setting will make the installation
of the pygame package (which is introduced later in the book) work correctly.
NOTE
I am aware of the “PEP 8 – Style Guide for Python Code” and
its specific recommendation to use the snake case convention
(snake_case) for variable and function names. However, I’d
been using the camel case naming convention (camelCase) for
many years before the PEP 8 document was written and have
become comfortable with it during my career. Therefore, all
variable and function names in this book are written using
camel case.
How Will I Explain OOP?
The examples in the first few chapters use text-based Python; these
sample programs get input from the user and output information to
the user purely in the form of text. I’ll introduce OOP by showing you
how to develop text-based simulations of physical objects in code.
We’ll start by creating representations of light switches, dimmer
switches, and TV remote controls as objects. I’ll then show you how
we can use OOP to simulate bank accounts and a bank that controls
many accounts.
Once we’ve covered the basics of OOP, I’ll introduce the pygame
module, which allows programmers to write games and applications
that use a graphical user interface (GUI). With GUI-based programs,
the user intuitively interacts with buttons, checkboxes, text input and
output fields, and other user-friendly widgets.
I chose to use pygame with Python because this combination
allows me to demonstrate OOP concepts in a highly visual way using
elements on the screen. Pygame is extremely portable and runs on
nearly every platform and operating system. All the sample programs
that use the pygame package have been tested with the recently
released pygame version 2.0.
I’ve created a package called pygwidgets that works with pygame
and implements a number of basic widgets, all of which are built
using an OOP approach. I’ll introduce this package later in the book,
providing sample code you can run and experiment with. This
approach will allow you to see real, practical examples of key object-
oriented concepts, while incorporating these techniques to produce
fun, playable games. I’ll also introduce my pyghelpers package,
which provides code to help write more complicated games and
applications.
All the example code shown in the book is available as a single
download from the No Starch website:
https://www.nostarch.com/object-oriented-python/.
The code is also available on a chapter-by-chapter basis from my
GitHub repository: https://github.com/IrvKalb/Object-Oriented-
Python-Code/.
What’s in the Book
This book is divided into four parts. Part I introduces object-oriented
programming:
Chapter 1 provides a review of coding using procedural
programming. I’ll show you how to implement a text-based card
game and simulate a bank performing operations on one or more
accounts. Along the way, I discuss common problems with the
procedural approach.
Chapter 2 introduces classes and objects and shows how you can
represent real-world objects like light switches or a TV remote in
Python using classes. You’ll see how an object-oriented approach
solves the problems highlighted in the first chapter.
Chapter 3 presents two mental models that you can use to think
about what’s going on behind the scenes when you create objects in
Python. We’ll use Python Tutor to step through code and see how
objects are created.
Chapter 4 demonstrates a standard way to handle multiple objects of
the same type by introducing the concept of an object manager
object. We’ll expand the bank account simulation using classes, and
I’ll show you how to handle errors using exceptions.
Part II focuses on building GUIs with pygame:
Chapter 5 introduces the pygame package and the event-driven
model of programming. We’ll build a few simple programs to get you
started with placing graphics in a window and handling keyboard and
mouse input, then develop a more complicated ball-bouncing
program.
Chapter 6 goes into much more detail on using OOP with pygame
programs. We’ll rewrite the ball-bouncing program in an OOP style
and develop some simple GUI elements.
Chapter 7 introduces the pygwidgets module, which contains full
implementations of many standard GUI elements (buttons,
checkboxes, and so on), each developed as a class.
Part III delves into the main tenets of OOP:
Chapter 8 discusses encapsulation, which involves hiding
implementation details from external code and placing all related
methods in one place: a class.
Chapter 9 introduces polymorphism—the idea that multiple classes
can have methods with the same names—and shows how it enables
you to make calls to methods in multiple objects, without having to
know the type of each object. We’ll build a Shapes program to
demonstrate this concept.
Chapter 10 covers inheritance, which allows you to create a set of
subclasses that all use common code built into a base class, rather
than having to reinvent the wheel with similar classes. We’ll look at a
few real-world examples where inheritance comes in handy, such as
implementing an input field that only accepts numbers, then rewrite
our Shapes example program to use this feature.
Chapter 11 wraps up this part of the book by discussing some
additional important OOP topics, mostly related to memory
management. We’ll look at the lifetime of an object, and as an
example we’ll build a small balloon-popping game.
Part IV explores several topics related to using OOP in game
development:
Chapter 12 demonstrates how we can rebuild the card game
developed in Chapter 1 as a pygame-based GUI program. I also
show you how to build reusable Deck and Card classes that you can
use in other card games you create.
Chapter 13 covers timing. We’ll develop different timer classes that
allow a program to keep running while concurrently checking for a
given time limit.
Chapter 14 explains animation classes you can use to show
sequences of images. We’ll look at two animation techniques:
building animations from a collection of separate image files and
extracting and using multiple images from a single sprite sheet file.
Chapter 15 explains the concept of a state machine, which
represents and controls the flow of your programs, and a scene
manager, which you can use to build a program with multiple scenes.
To demonstrate the use of each of these, we’ll build two versions of a
Rock, Paper, Scissors game.
Chapter 16 discusses different types of modal dialogs, another
important user interaction feature. We then walk through building a
full-featured OOP-based video game called Dodger that
demonstrates many of the techniques described in the book.
Chapter 17 introduces the concept of design patterns, focusing on
the Model View Controller pattern, then presents a dice-rolling
program that uses this pattern to allow the user to visualize data in
numerous different ways. It concludes with a short wrap-up for the
book.
Development Environments
In this book, you’ll need to use the command line only minimally for
installing software. All installation instructions will be clearly written
out, so you won’t need to learn any additional command line syntax.
Rather than using the command line for development, I believe
strongly in using an interactive development environment (IDE). An
IDE handles many of the details of the underlying operating system
for you, and it allows you to write, edit, and run your code using a
single program. IDEs are typically cross-platform, allowing
programmers to easily move from a Mac to a Windows computer or
vice versa.
The short example programs in the book can be run in the IDLE
development environment that is installed when you install Python.
IDLE is very simple to use and works well for programs that can be
written in a single file. When we get into more complicated programs
that use multiple Python files, I encourage you to use a more
sophisticated environment instead; I use the JetBrains PyCharm
development environment, which handles multiple-file projects more
easily. The Community Edition is available for free from
https://www.jetbrains.com/, and I highly recommend it. PyCharm also
has a fully integrated debugger that can be extremely useful when
writing larger programs. For more information on how to use the
debugger, please see my YouTube video “Debugging Python 3 with
PyCharm” at https://www.youtube.com/watch?
v=cxAOSQQwDJ4&t=43s/.
Widgets and Example Games
The book introduces and makes available two Python packages:
pygwidgets and pyghelpers. Using these packages, you should be
able to build full GUI programs—but more importantly, you should
gain an understanding of how each of the widgets is coded as a
class and used as an object.
Incorporating various widgets, the example games in the book
start out relatively simple and get progressively more complicated.
Chapter 16 walks you through the development and implementation
of a full-featured video game, complete with a high-scores table that
is saved to a file.
By the end of this book, you should be able to code your own
games—card games, or video games in the style of Pong,
Hangman, Breakout, Space Invaders, and so on. Object-oriented
programming gives you the ability to write programs that can easily
display and control multiple items of the same type, which is often
required when building user interfaces and is frequently necessary in
game play.
Object-oriented programming is a general style that can be used in
all aspects of programming, well beyond the game examples I use to
demonstrate OOP techniques here. I hope you find this approach to
learning OOP enjoyable.
Let’s get started!
PART I
INTRODUCING OBJECT-ORIENTED
PROGRAMMING
This part of the book introduces you to object-
oriented programming. We’ll discuss problems
inherent in procedural code, then see how
object-oriented programming addresses those
concerns. Thinking in objects (with state and
behavior) will give you a new perspective about
how to write code.
Chapter 1 provides a review of procedural Python. I start by
presenting a text-based card game named Higher or Lower, then
work through a few progressively more complex implementations of
a bank account in Python to help you better understand common
problems with coding in a procedural style.
Chapter 2 shows how we might represent real-world objects in
Python using classes. We’ll write a program to simulate a light
switch, modify it to include dimming capabilities, then move on to a
more complicated TV remote simulation.
Chapter 3 gives you two different ways to think about what is
going on behind the scenes when you create objects in Python.
Chapter 4 then demonstrates a standard way to handle multiple
objects of the same type (for example, consider a simple game like
checkers where you have to keep track of many similar game
pieces). We’ll expand the bank account programs from Chapter 1,
and explore how to handle errors.
1
PROCEDURAL PYTHON EXAMPLES
Introductory courses and books
typically teach software
development using the procedural
programming style, which involves
splitting a program into a number of
functions (also known as procedures or
subroutines). You pass data into functions, each
of which performs one or more computations
and, typically, passes back results. This book is
about a different paradigm of programming
known as object-oriented programming (OOP)
that allows programmers to think differently
about how to build software. Object-oriented
programming gives programmers a way to
combine code and data together into cohesive
units, thereby avoiding some complications
inherent in procedural programming.
In this chapter, I’ll review a number of concepts in basic Python by
building two small programs that incorporate various Python
constructs. The first will be a small card game called Higher or
Lower; the second will be a simulation of a bank, performing
operations on one, two, and multiple accounts. Both will be built
using procedural programming—that is, using the standard
techniques of data and functions. Later, I’ll rewrite these programs
using OOP techniques. The purpose of this chapter is to
demonstrate some key problems inherent in procedural
programming. With that understanding, the chapters that follow will
explain how OOP solves those problems.
Higher or Lower Card Game
My first example is a simple card game called Higher or Lower. In
this game, eight cards are randomly chosen from a deck. The first
card is shown face up. The game asks the player to predict whether
the next card in the selection will have a higher or lower value than
the currently showing card. For example, say the card that’s shown
is a 3. The player chooses “higher,” and the next card is shown. If
that card has a higher value, the player is correct. In this example, if
the player had chosen “lower,” they would have been incorrect.
If the player guesses correctly, they get 20 points. If they choose
incorrectly, they lose 15 points. If the next card to be turned over has
the same value as the previous card, the player is incorrect.
Representing the Data
The program needs to represent a deck of 52 cards, which I’ll build
as a list. Each of the 52 elements in the list will be a dictionary (a set
of key/value pairs). To represent any card, each dictionary will
contain three key/value pairs: 'rank', 'suit', and 'value'. The rank
is the name of the card (Ace, 2, 3, … 10, Jack, Queen, King), but the
value is an integer used for comparing cards (1, 2, 3, … 10, 11, 12,
13). For example, the Jack of Clubs would be represented as the
following dictionary:
{'rank': 'Jack', 'suit': 'Clubs', 'value': 11}
Before the player plays a round, the list representing the deck is
created and shuffled to randomize the order of the cards. I have no
graphical representation of the cards, so each time the user chooses
“higher” or “lower,” the program gets a card dictionary from the deck
and prints the rank and the suit for the user. The program then
compares the value of the new card to that of the previous card and
gives feedback based on the correctness of the user’s answer.
Implementation
Listing 1-1 shows the code of the Higher or Lower game.
NOTE
As a reminder, the code associated with all the major listings
in this book is available for download at
https://www.nostarch.com/object-oriented-python/ and
https://github.com/IrvKalb/Object-Oriented-Python-Code/. You
can either download and run the code or type it in yourself.
File: HigherOrLowerProcedural.py
# HigherOrLower
import random
# Card constants
SUIT_TUPLE = ('Spades', 'Hearts', 'Clubs', 'Diamonds')
RANK_TUPLE = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9',
'10', 'Jack', 'Queen', 'King')
NCARDS = 8
# Pass in a deck and this function returns a random card from
the deck
def getCard(deckListIn):
thisCard = deckListIn.pop() # pop one off the top of the
deck and return
return thisCard
# Pass in a deck and this function returns a shuffled copy of
the deck
def shuffle(deckListIn):
deckListOut = deckListIn.copy() # make a copy of the
starting deck
random.shuffle(deckListOut)
return deckListOut
# Main code
print('Welcome to Higher or Lower.')
print('You have to choose whether the next card to be shown
will be higher or lower than the current card.')
print('Getting it right adds 20 points; get it wrong and you
lose 15 points.')
print('You have 50 points to start.')
print()
startingDeckList = []
1 for suit in SUIT_TUPLE:
for thisValue, rank in enumerate(RANK_TUPLE):
cardDict = {'rank':rank, 'suit':suit,
'value':thisValue + 1}
startingDeckList.append(cardDict)
score = 50
while True: # play multiple games
print()
gameDeckList = shuffle(startingDeckList)
2 currentCardDict = getCard(gameDeckList)
currentCardRank = currentCardDict['rank']
currentCardValue = currentCardDict['value']
currentCardSuit = currentCardDict['suit']
print('Starting card is:', currentCardRank + ' of ' +
currentCardSuit)
print()
3 for cardNumber in range(0, NCARDS): # play one game of
this many cards
answer = input('Will the next card be higher or lower
than the ' +
currentCardRank + ' of ' +
currentCardSuit + '? (enter h or l):
')
answer = answer.casefold() # force lowercase
4 nextCardDict = getCard(gameDeckList)
nextCardRank = nextCardDict['rank']
nextCardSuit = nextCardDict['suit']
nextCardValue = nextCardDict['value']
print('Next card is:', nextCardRank + ' of ' +
nextCardSuit)
5 if answer == 'h':
if nextCardValue > currentCardValue:
print('You got it right, it was higher')
score = score + 20
else:
print('Sorry, it was not higher')
score = score - 15
elif answer == 'l':
if nextCardValue < currentCardValue:
score = score + 20
print('You got it right, it was lower')
else:
score = score - 15
print('Sorry, it was not lower')
print('Your score is:', score)
print()
currentCardRank = nextCardRank
currentCardValue = nextCardValue # don't need
current suit
6 goAgain = input('To play again, press ENTER, or "q" to
quit: ')
if goAgain == 'q':
break
print('OK bye')
Listing 1-1: A Higher or Lower game using procedural Python
The program starts by creating a deck as a list 1. Each card is a
dictionary made up of a rank, a suit, and a value. For each round of
the game, I retrieve the first card from the deck and save the
components in variables 2. For the next seven cards, the user is
asked to predict whether the next card will be higher or lower than
the most recently showing card 3. The next card is retrieved from the
deck, and its components are saved in a second set of variables 4.
The game compares the user’s answer to the card drawn and gives
the user feedback and points based on the outcome 5. When the
user has made predictions for all seven cards in the selection, we
ask if they want to play again 6.
This program demonstrates many elements of programming in
general and Python in particular: variables, assignment statements,
functions and function calls, if/else statements, print statements,
while loops, lists, strings, and dictionaries. This book will assume
you're already familiar with everything shown in this example. If there
is anything in this program that is unfamiliar or not clear to you, it
would probably be worth your time to review the appropriate material
before moving on.
Reusable Code
Since this is a playing card–based game, the code obviously creates
and manipulates a simulated deck of cards. If we wanted to write
another card-based game, it would be great to be able to reuse the
code for the deck and cards.
In a procedural program, it can often be difficult to identify all the
pieces of code associated with one portion of the program, such as
the deck and cards in this example. In Listing 1-1, the code for the
deck consists of two tuple constants, two functions, some main code
to build a global list that represents the starting deck of 52 cards, and
another global list that represents the deck that is used while the
game is being played. Further, notice that even in a small program
like this, the data and the code that manipulates the data might not
be closely grouped together.
Therefore, reusing the deck and card code in another program is
not that easy or straightforward. In Chapter 12, we will revisit this
program and show how an OOP solution makes reusing code like
this much easier.
Bank Account Simulations
In this second example of procedural coding, I’ll present a number of
variations of a program that simulates running a bank. In each new
version of the program, I’ll add more functionality. Note that these
programs are not production-ready; invalid user entries or misuse
will lead to errors. The intent is to have you focus on how the code
interacts with the data associated with one or more bank accounts.
To start, consider what operations a client would want to do with a
bank account and what data would be needed to represent an
account.
Analysis of Required Operations and Data
A list of operations a person would want to do with a bank account
would include:
Create (an account)
Deposit
Withdraw
Check balance
Next, here is a minimal list of the data we would need to represent
a bank account:
Customer name
Password
Balance
Notice that all the operations are action words (verbs) and all the
data items are things (nouns). A real bank account would certainly
be capable of many more operations and would contain additional
pieces of data (such as the account holder’s address, phone
number, and Social Security number), but to keep the discussion
clear, I’ll start with just these four actions and three pieces of data.
Further, to keep things simple and focused, I’ll make all amounts an
integer number of dollars. I should also point out that in a real bank
application, passwords would not be kept in cleartext (unencrypted)
as it is in these examples.
Implementation 1—Single Account Without Functions
In the starting version in Listing 1-2, there is only a single account.
File: Bank1_OneAccount.py
# Non-OOP
# Bank Version 1
# Single account
1 accountName = 'Joe'
accountBalance = 100
accountPassword = 'soup'
while True:
2 print()
print('Press b to get the balance')
print('Press d to make a deposit')
print('Press w to make a withdrawal')
print('Press s to show the account')
print('Press q to quit')
print()
action = input('What do you want to do? ')
action = action.lower() # force lowercase
action = action[0] # just use first letter
print()
if action == 'b':
print('Get Balance:')
userPassword = input('Please enter the password: ')
if userPassword != accountPassword:
print('Incorrect password')
else:
print('Your balance is:', accountBalance)
elif action == 'd':
print('Deposit:')
userDepositAmount = input('Please enter amount to
deposit: ')
userDepositAmount = int(userDepositAmount)
userPassword = input('Please enter the password: ')
if userDepositAmount < 0:
print('You cannot deposit a negative amount!')
elif userPassword != accountPassword:
print('Incorrect password')
else: # OK
accountBalance = accountBalance +
userDepositAmount
print('Your new balance is:', accountBalance)
elif action == 's': # show
print('Show:')
print(' Name', accountName)
print(' Balance:', accountBalance)
print(' Password:', accountPassword)
print()
elif action == 'q':
break
elif action == 'w':
print('Withdraw:')
userWithdrawAmount = input('Please enter the amount
to withdraw: ')
userWithdrawAmount = int(userWithdrawAmount)
userPassword = input('Please enter the password: ')
if userWithdrawAmount < 0:
print('You cannot withdraw a negative amount')
elif userPassword != accountPassword:
print('Incorrect password for this account')
elif userWithdrawAmount > accountBalance:
print('You cannot withdraw more than you have in
your account')
else: #OK
accountBalance = accountBalance -
userWithdrawAmount
print('Your new balance is:', accountBalance)
print('Done')
Listing 1-2: Bank simulation for a single account
The program starts off by initializing three variables to represent
the data of one account 1. Then it displays a menu that allows a
choice of operations 2. The main code of the program acts directly
on the global account variables.
In this example, all the actions are at the main level; there are no
functions in the code. The program works fine, but it may seem a
little long. A typical approach to make longer programs clearer is to
move related code into functions and make calls to those functions.
We’ll explore that in the next implementation of the banking program.
Implementation 2—Single Account with Functions
In the version of the program in Listing 1-3, the code is broken up
into separate functions, one for each action. Again, this simulation is
for a single account.
File: Bank2_OneAccountWithFunctions.py
# Non-OOP
# Bank 2
# Single account
accountName = ''
accountBalance = 0
accountPassword = ''
1 def newAccount(name, balance, password):
global accountName, accountBalance, accountPassword
accountName = name
accountBalance = balance
accountPassword = password
def show():
global accountName, accountBalance, accountPassword
print(' Name', accountName)
print(' Balance:', accountBalance)
print(' Password:', accountPassword)
print()
2 def getBalance(password):
global accountName, accountBalance, accountPassword
if password != accountPassword:
print('Incorrect password')
return None
return accountBalance
3 def deposit(amountToDeposit, password):
global accountName, accountBalance, accountPassword
if amountToDeposit < 0:
print('You cannot deposit a negative amount!')
return None
if password != accountPassword:
print('Incorrect password')
return None
accountBalance = accountBalance + amountToDeposit
return accountBalance
4 def withdraw(amountToWithdraw, password):
5 global accountName, accountBalance, accountPassword
if amountToWithdraw < 0:
print('You cannot withdraw a negative amount')
return None
if password != accountPassword:
print('Incorrect password for this account')
return None
if amountToWithdraw > accountBalance:
print('You cannot withdraw more than you have in your
account')
return None
6 accountBalance = accountBalance - amountToWithdraw
return accountBalance
newAccount("Joe", 100, 'soup') # create an account
while True:
print()
print('Press b to get the balance')
print('Press d to make a deposit')
print('Press w to make a withdrawal')
print('Press s to show the account')
print('Press q to quit')
print()
action = input('What do you want to do? ')
action = action.lower() # force lowercase
action = action[0] # just use first letter
print()
if action == 'b':
print('Get Balance:')
userPassword = input('Please enter the password: ')
theBalance = getBalance(userPassword)
if theBalance is not None:
print('Your balance is:', theBalance)
7 elif action == 'd':
print('Deposit:')
userDepositAmount = input('Please enter amount to
deposit: ')
userDepositAmount = int(userDepositAmount)
userPassword = input('Please enter the password: ')
8 newBalance = deposit(userDepositAmount, userPassword)
if newBalance is not None:
print('Your new balance is:', newBalance)
--- snip calls to appropriate functions ---
print('Done')
Listing 1-3: Bank simulation for one account with functions
In this version, I’ve built a function for each of the operations that
we identified for a bank account (create 1, check balance 2, deposit
3, and withdraw 4) and rearranged the code so that the main code
contains calls to the different functions.
As a result, the main program is much more readable. For
example, if the user types d to indicate that they want to make a
deposit 7, the code now calls a function named deposit() 3, passing
in the amount to be deposited and the account password the user
entered.
However, if you look at the definition of any of these functions—for
example, the withdraw() function—you’ll see that the code uses
global statements 5 to access (get or set) the variables that
represent the account. In Python, a global statement is only required
if you want to change the value of a global variable in a function.
However, I am using them here to make it clear that these functions
are referring to global variables, even if they are just getting a value.
As a general programming tenet, functions should never modify
global variables. A function should only use data that is passed into
it, make calculations based on that data, and potentially return a
result or results. The withdraw() function in this program does work,
but it violates this rule by modifying the value of the global variable
accountBalance 6 (in addition to accessing the value of the global
variable accountPassword).
Implementation 3—Two Accounts
The version of the bank simulation program in Listing 1-4 uses the
same approach as Listing 1-3 but adds the ability to have two
accounts.
File: Bank3_TwoAccounts.py
# Non-OOP
# Bank 3
# Two accounts
account0Name = ''
account0Balance = 0
account0Password = ''
account1Name = ''
account1Balance = 0
account1Password = ''
nAccounts = 0
def newAccount(accountNumber, name, balance, password):
1 global account0Name, account0Balance, account0Password
global account1Name, account1Balance, account1Password
if accountNumber == 0:
account0Name = name
account0Balance = balance
account0Password = password
if accountNumber == 1:
account1Name = name
account1Balance = balance
account1Password = password
def show():
2 global account0Name, account0Balance, account0Password
global account1Name, account1Balance, account1Password
if account0Name != '':
print('Account 0')
print(' Name', account0Name)
print(' Balance:', account0Balance)
print(' Password:', account0Password)
print()
if account1Name != '':
print('Account 1')
print(' Name', account1Name)
print(' Balance:', account1Balance)
print(' Password:', account1Password)
print()
def getBalance(accountNumber, password):
3 global account0Name, account0Balance, account0Password
global account1Name, account1Balance, account1Password
if accountNumber == 0:
if password != account0Password:
print('Incorrect password')
return None
return account0Balance
if accountNumber == 1:
if password != account1Password:
print('Incorrect password')
return None
return account1Balance
--- snipped additional deposit() and withdraw() functions ---
--- snipped main code that calls functions above ---
print('Done')
Listing 1-4: Bank simulation for two accounts with functions
Even with just two accounts, you can see that this approach gets
out of hand quickly. First, we set three global variables for each
account at 1, 2, and 3. Also, every function now has an if statement
to choose which set of global variables to access or change. Any
time we want to add another account, we’ll need to add another set
of global variables and more if statements in every function. This is
simply not a feasible approach. We need a different way to handle
an arbitrary number of accounts.
Implementation 4—Multiple Accounts Using Lists
To more easily accommodate multiple accounts, in Listing 1-5 I’ll
represent the data using lists. I’ll use three parallel lists in this
version of the program: accountNamesList, accountPasswordsList,
and accountBalancesList.
File: Bank4_N_Accounts.py
# Non-OOP Bank
# Version 4
# Any number of accounts - with lists
1 accountNamesList = []
accountBalancesList = []
accountPasswordsList = []
def newAccount(name, balance, password):
global accountNamesList, accountBalancesList,
accountPasswordsList
2 accountNamesList.append(name)
accountBalancesList.append(balance)
accountPasswordsList.append(password)
def show(accountNumber):
global accountNamesList, accountBalancesList,
accountPasswordsList
print('Account', accountNumber)
print(' Name', accountNamesList[accountNumber])
print(' Balance:',
accountBalancesList[accountNumber])
print(' Password:',
accountPasswordsList[accountNumber])
print()
def getBalance(accountNumber, password):
global accountNamesList, accountBalancesList,
accountPasswordsList
if password != accountPasswordsList[accountNumber]:
print('Incorrect password')
return None
return accountBalancesList[accountNumber]
--- snipped additional functions ---
# Create two sample accounts
3 print("Joe's account is account number:",
len(accountNamesList))
newAccount("Joe", 100, 'soup')
4 print("Mary's account is account number:",
len(accountNamesList))
newAccount("Mary", 12345, 'nuts')
while True:
print()
print('Press b to get the balance')
print('Press d to make a deposit')
print('Press n to create a new account')
print('Press w to make a withdrawal')
print('Press s to show all accounts')
print('Press q to quit')
print()
action = input('What do you want to do? ')
action = action.lower() # force lowercase
action = action[0] # just use first letter
print()
if action == 'b':
print('Get Balance:')
5 userAccountNumber = input('Please enter your account
number: ')
userAccountNumber = int(userAccountNumber)
userPassword = input('Please enter the password: ')
theBalance = getBalance(userAccountNumber,
userPassword)
if theBalance is not None:
print('Your balance is:', theBalance)
--- snipped additional user interface ---
print('Done')
Listing 1-5: Bank simulation with a parallel lists
At the beginning of the program, I set all three lists to the empty
list 1. To create a new account, I append the appropriate value to
each of the three lists 2.
Since I am now dealing with multiple accounts, I use the basic
concept of a bank account number. Every time a user creates an
account, the code uses the len() function on one of the lists and
returns that number as the user’s account number 3, 4. When I
create an account for the first user, the length of the
accountNamesList is zero. Therefore, the first account created will be
given account number 0, the second account is given account
number 1, and so on. Then, like at a real bank, to do any operation
after creating an account (like deposit or withdraw funds), the user
must supply their account number 5.
However, this code is still working with global data; now there are
three global lists of data.
Imagine viewing this data as a spreadsheet. It might look like
Table 1-1.
Table 1-1: A Table of Our Data
Account number Name Password Balance
0 Joe soup 100
1 Mary nuts 3550
2 Bill frisbee 1000
3 Sue xxyyzz 750
4 Henry PW 10000
The data is maintained as three global Python lists, where each
list represents a column in this table. For example, as you can see
from the highlighted column, all the passwords are grouped together
as one list. The users’ names are grouped in another list, and the
balances are grouped in a third list. With this approach, to get
information about one account, you need to access these lists with a
common index value.
While this works, it seems extremely awkward. The data is not
grouped in a logical way. For example, it doesn’t seem right to keep
all users’ passwords together. Further, every time you add a new
attribute to an account, like an address or phone number, you need
to create and access another global list.
Instead, what you really want is a grouping that represents a row
in the same spreadsheet, as in Table 1-2.
Table 1-2: A Table of Our Data
Account number Name Password Balance
0 Joe soup 100
1 Mary nuts 3550
2 Bill frisbee 1000
3 Sue xxyyzz 750
4 Henry PW 10000
With this approach, each row represents the data associated with
a single bank account. While this is the same data, this grouping is a
much more natural way of representing an account.
Implementation 5—List of Account Dictionaries
To implement this last approach, I’ll use a slightly more complicated
data structure. In this version, I’ll create a list of accounts, where
each account (each element of this list) is a dictionary that looks like
this:
{'name':<someName>, 'password':<somePassword>, 'balance':
<someBalance>}
NOTE
In this book, whenever I present a value in angle brackets
(<>), this means you should replace that item (including the
brackets) with a value of your choosing. For example, in the
preceding code line, <someName>, <somePassword>, and
<someBalance> are placeholders and should be replaced with
actual values.
The code for the final implementation is presented in Listing 1-6.
File: Bank5_Dictionary.py
# Non-OOP Bank
# Version 5
# Any number of accounts - with a list of dictionaries
accountsList = [] 1
def newAccount(aName, aBalance, aPassword):
global accountsList
newAccountDict = {'name':aName, 'balance':aBalance,
'password':aPassword}
accountsList.append(newAccountDict) 2
def show(accountNumber):
global accountsList
print('Account', accountNumber)
thisAccountDict = accountsList[accountNumber]
print(' Name', thisAccountDict['name'])
print(' Balance:', thisAccountDict['balance'])
print(' Password:', thisAccountDict['password'])
print()
def getBalance(accountNumber, password):
global accountsList
thisAccountDict = accountsList[accountNumber] 3
if password != thisAccountDict['password']:
print('Incorrect password')
return None
return thisAccountDict['balance']
Another Random Document on
Scribd Without Any Related Topics
Ah, God! What had she done! How had she dared to throw away
her happiness like this. This was the only man who had ever
understood her. Was it too late? Could it be too late? She was that
glove that he held in his fingers. . . .
“And then the fact that you had no friends and never had made
friends with people. How I understood that, for neither had I. Is it
just the same now?”
“Yes,” she breathed. “Just the same. I am as alone as ever.”
“So am I,” he laughed gently, “just the same.”
Suddenly with a quick gesture he handed her back the glove and
scraped his chair on the floor, “But what seemed to me so
mysterious then is perfectly plain to me now. And to you, too, of
course. . . . It simply was that we were such egoists, so self-
engrossed, so wrapped up in ourselves that we hadn’t a corner in
our hearts for anybody else. Do you know,” he cried, naive and
hearty, and dreadfully like another side of that old self again, “I
began studying a Mind System when I was in Russia, and I found
that we were not peculiar at all. It’s quite a well known form of . . .”
She had gone. He sat there, thunder-struck, astounded beyond
words. . . . And then he asked the waitress for his bill.
“But the cream has not been touched,” he said. “Please do not
charge me for it.”
The Little Governess
Oh, dear, how she wished that it wasn’t night-time. She’d have
much rather travelled by day, much much rather. But the lady at the
Governess Bureau had said: “You had better take an evening boat
and then if you get into a compartment for ‘Ladies Only’ in the train
you will be far safer than sleeping in a foreign hotel. Don’t go out of
the carriage; don’t walk about the corridors and be sure to lock the
lavatory door if you go there. The train arrives at Munich at eight
o’clock, and Frau Arnholdt says that the Hotel Grunewald is only one
minute away. A porter can take you there. She will arrive at six the
same evening, so you will have a nice quiet day to rest after the
journey and rub up your German. And when you want anything to
eat I would advise you to pop into the nearest baker’s and get a bun
and some coffee. You haven’t been abroad before, have you?” “No.”
“Well, I always tell my girls that it’s better to mistrust people at first
rather than trust them, and it’s safer to suspect people of evil
intentions rather than good ones. . . . It sounds rather hard but
we’ve got to be women of the world, haven’t we?”
It had been nice in the Ladies’ Cabin. The stewardess was so kind
and changed her money for her and tucked up her feet. She lay on
one of the hard pink-sprigged couches and watched the other
passengers, friendly and natural, pinning their hats to the bolsters,
taking off their boots and skirts, opening dressing-cases and
arranging mysterious rustling little packages, tying their heads up in
veils before lying down. Thud, thud, thud, went the steady screw of
the steamer. The stewardess pulled a green shade over the light and
sat down by the stove, her skirt turned back over her knees, a long
piece of knitting on her lap. On a shelf above her head there was a
water-bottle with a tight bunch of flowers stuck in it. “I like travelling
very much,” thought the little governess. She smiled and yielded to
the warm rocking.
But when the boat stopped and she went up on deck, her dress-
basket in one hand, her rug and umbrella in the other, a cold,
strange wind flew under her hat. She looked up at the masts and
spars of the ship black against a green glittering sky and down to
the dark landing stage where strange muffled figures lounged,
waiting; she moved forward with the sleepy flock, all knowing where
to go to and what to do except her, and she felt afraid. Just a little—
just enough to wish—oh, to wish that it was daytime and that one of
those women who had smiled at her in the glass, when they both
did their hair in the Ladies’ Cabin, was somewhere near now.
“Tickets, please. Show your tickets. Have your tickets ready.” She
went down the gangway balancing herself carefully on her heels.
Then a man in a black leather cap came forward and touched her on
the arm. “Where for, Miss?” He spoke English—he must be a guard
or a stationmaster with a cap like that. She had scarcely answered
when he pounced on her dress-basket. “This way,” he shouted, in a
rude, determined voice, and elbowing his way he strode past the
people. “But I don’t want a porter.” What a horrible man! “I don’t
want a porter. I want to carry it myself.” She had to run to keep up
with him, and her anger, far stronger than she, ran before her and
snatched the bag out of the wretch’s hand. He paid no attention at
all, but swung on down the long dark platform, and across a railway
line. “He is a robber.” She was sure he was a robber as she stepped
between the silvery rails and felt the cinders crunch under her
shoes. On the other side—oh, thank goodness!—there was a train
with Munich written on it. The man stopped by the huge lighted
carriages. “Second class?” asked the insolent voice. “Yes, a Ladies’
compartment.” She was quite out of breath. She opened her little
purse to find something small enough to give this horrible man while
he tossed her dress-basket into the rack of an empty carriage that
had a ticket, Dames Seules, gummed on window. She got into the
train and handed twenty centimes. “What’s this?” shouted the man,
glaring at the money and then at her, holding it up to his nose,
sniffing at it as though he had never in his life seen, much less held,
such a sum. “It’s a franc. You know that, don’t you? It’s a franc.
That’s my fare!” A franc! Did he imagine that she was going to give
him a franc for playing a trick like that just because she was a girl
and travelling alone at night? Never, never! She squeezed her purse
in her hand and simply did not see him—she looked at a view of St.
Malo on the wall opposite and simply did not hear him. “Ah, no. Ah,
no. Four sous. You make a mistake. Here, take it. It’s a franc I
want.” He leapt on to the step of the train and threw the money on
to her lap. Trembling with terror she screwed herself tight, tight, and
put out an icy hand and took the money—stowed it away in her
hand. “That’s all you’re going to get,” she said. For a minute or two
she felt his sharp eyes pricking her all over, while he nodded slowly,
pulling down his mouth: “Ve-ry well. Trrrès bien.” He shrugged his
shoulders and disappeared into the dark. Oh, the relief! How simply
terrible that had been! As she stood up to feel if the dress-basket
was firm she caught sight of herself in the mirror, quite white, with
big round eyes. She untied her “motor veil” and unbuttoned her
green cape. “But it’s all over now,” she said to the mirror face,
feeling in some way that it was more frightened than she.
People began to assemble on the platform. They stood together in
little groups talking; a strange light from the station lamps painted
their faces almost green. A little boy in red clattered up with a huge
tea wagon and leaned against it, whistling and flicking his boots with
a serviette. A woman in a black alpaca apron pushed a barrow with
pillows for hire. Dreamy and vacant she looked—like a woman
wheeling a perambulator—up and down, up and down—with a
sleeping baby inside it. Wreaths of white smoke floated up from
somewhere and hung below the roof like misty vines. “How strange
it all is,” thought the little governess, “and the middle of the night,
too.” She looked out from her safe corner, frightened no longer but
proud that she had not given that franc. “I can look after myself—of
course I can. The great thing is not to——” Suddenly from the
corridor there came a stamping of feet and men’s voices, high and
broken with snatches of loud laughter. They were coming her way.
The little governess shrank into her corner as four young men in
bowler hats passed, staring through the door and window. One of
them, bursting with the joke, pointed to the notice Dames Seules
and the four bent down the better to see the one little girl in the
corner. Oh dear, they were in the carriage next door. She heard them
tramping about and then a sudden hush followed by a tall thin fellow
with a tiny black moustache who flung her door open. “If
mademoiselle cares to come in with us,” he said, in French. She saw
the others crowding behind him, peeping under his arm and over his
shoulder, and she sat very straight and still. “If mademoiselle will do
us the honour,” mocked the tall man. One of them could be quiet no
longer; his laughter went off in a loud crack. “Mademoiselle is
serious,” persisted the young man, bowing and grimacing. He took
off his hat with a flourish, and she was alone again.
“En voiture. En voi-ture!” Some one ran up and down beside the
train. “I wish it wasn’t night-time. I wish there was another woman
in the carriage. I’m frightened of the men next door.” The little
governess looked out to see her porter coming back again—the
same man making for her carriage with his arms full of luggage. But
—but what was he doing? He put his thumb nail under the label
Dames Seules and tore it right off and then stood aside squinting at
her while an old man wrapped in a plaid cape climbed up the high
step. “But this is a ladies’ compartment.” “Oh, no, Mademoiselle, you
make a mistake. No, no, I assure you. Merci, Monsieur.” “En voi-
turre!” A shrill whistle. The porter stepped off triumphant and the
train started. For a moment or two big tears brimmed her eyes and
through them she saw the old man unwinding a scarf from his neck
and untying the flaps of his Jaeger cap. He looked very old. Ninety
at least. He had a white moustache and big gold-rimmed spectacles
with little blue eyes behind them and pink wrinkled cheeks. A nice
face—and charming the way he bent forward and said in halting
French: “Do I disturb you, Mademoiselle? Would you rather I took all
these things out of the rack and found another carriage?” What! that
old man have to move all those heavy things just because she . . .
“No, it’s quite all right. You don’t disturb me at all.” “Ah, a thousand
thanks.” He sat down opposite her and unbuttoned the cape of his
enormous coat and flung it off his shoulders.
The train seemed glad to have left the station. With a long leap it
sprang into the dark. She rubbed a place in the window with her
glove but she could see nothing—just a tree outspread like a black
fan or a scatter of lights, or the line of a hill, solemn and huge. In
the carriage next door the young men started singing “Un, deux,
trois.” They sang the same song over and over at the tops of their
voices.
“I never could have dared to go to sleep if I had been alone,” she
decided. “I couldn’t have put my feet up or even taken off my hat.”
The singing gave her a queer little tremble in her stomach and,
hugging herself to stop it, with her arms crossed under her cape,
she felt really glad to have the old man in the carriage with her.
Careful to see that he was not looking she peeped at him through
her long lashes. He sat extremely upright, the chest thrown out, the
chin well in, knees pressed together, reading a German paper. That
was why he spoke French so funnily. He was a German. Something
in the army, she supposed—a Colonel or a General—once, of course,
not now; he was too old for that now. How spick and span he looked
for an old man. He wore a pearl pin stuck in his black tie and a ring
with a dark red stone on his little finger; the tip of a white silk
handkerchief showed in the pocket of his double-breasted jacket.
Somehow, altogether, he was really nice to look at. Most old men
were so horrid. She couldn’t bear them doddery—or they had a
disgusting cough or something. But not having a beard—that made
all the difference—and then his cheeks were so pink and his
moustache so very white. Down went the German paper and the old
man leaned forward with the same delightful courtesy: “Do you
speak German, Mademoiselle?” “Ja, ein wenig, mehr als
Franzosisch,” said the little governess, blushing a deep pink colour
that spread slowly over her cheeks and made her blue eyes look
almost black. “Ach, so!” The old man bowed graciously. “Then
perhaps you would care to look at some illustrated papers.” He
slipped a rubber band from a little roll of them and handed them
across. “Thank you very much.” She was very fond of looking at
pictures, but first she would take off her hat and gloves. So she
stood up, unpinned the brown straw and put it neatly in the rack
beside the dress-basket, stripped off her brown kid gloves, paired
them in a tight roll and put them in the crown of the hat for safety,
and then sat down again, more comfortably this time, her feet
crossed, the papers on her lap. How kindly the old man in the corner
watched her bare little hand turning over the big white pages,
watched her lips moving as she pronounced the long words to
herself, rested upon her hair that fairly blazed under the light. Alas!
how tragic for a little governess to possess hair that made one think
of tangerines and marigolds, of apricots and tortoiseshell cats and
champagne! Perhaps that was what the old man was thinking as he
gazed and gazed, and that not even the dark ugly clothes could
disguise her soft beauty. Perhaps the flush that licked his cheeks and
lips was a flush of rage that anyone so young and tender should
have to travel alone and unprotected through the night. Who knows
he was not murmuring in his sentimental German fashion: “Ja, es ist
eine Tragœdie! Would to God I were the child’s grandpapa!”
“Thank you very much. They were very interesting.” She smiled
prettily handing back the papers. “But you speak German extremely
well,” said the old man. “You have been in Germany before, of
course?” “Oh no, this is the first time”—a little pause, then—“this is
the first time that I have ever been abroad at all.” “Really! I am
surprised. You gave me the impression, if I may say so, that you
were accustomed to travelling.” “Oh, well—I have been about a good
deal in England, and to Scotland, once.” “So. I myself have been in
England once, but I could not learn English.” He raised one hand and
shook his head, laughing. “No, it was too difficult for me. . . . ‘Ow-
do-you-do. Please vich is ze vay to Leicestaire Squaare.’” She
laughed too. “Foreigners always say . . .” They had quite a little talk
about it. “But you will like Munich,” said the old man. “Munich is a
wonderful city. Museums, pictures, galleries, fine buildings and
shops, concerts, theatres, restaurants—all are in Munich. I have
travelled all over Europe many, many times in my life, but it is
always to Munich that I return. You will enjoy yourself there.” “I am
not going to stay in Munich,” said the little governess, and she added
shyly, “I am going to a post as governess to a doctor’s family in
Augsburg.” “Ah, that was it.” Augsburg he knew. Augsburg—well—
was not beautiful. A solid manufacturing town. But if Germany was
new to her he hoped she would find something interesting there too.
“I am sure I shall.” “But what a pity not to see Munich before you
go. You ought to take a little holiday on your way”—he smiled—“and
store up some pleasant memories.” “I am afraid I could not do that,”
said the little governess, shaking her head, suddenly important and
serious. “And also, if one is alone . . .” He quite understood. He
bowed, serious too. They were silent after that. The train shattered
on, baring its dark, flaming breast to the hills and to the valleys. It
was warm in the carriage. She seemed to lean against the dark
rushing and to be carried away and away. Little sounds made
themselves heard; steps in the corridor, doors opening and shutting
—a murmur of voices—whistling. . . . Then the window was pricked
with long needles of rain. . . . But it did not matter . . . it was
outside . . . and she had her umbrella . . . she pouted, sighed,
opened and shut her hands once and fell fast asleep.
“Pardon! Pardon!” The sliding back of the carriage door woke her
with a start. What had happened? Some one had come in and gone
out again. The old man sat in his corner, more upright than ever, his
hands in the pockets of his coat, frowning heavily. “Ha! ha! ha!”
came from the carriage next door. Still half asleep, she put her
hands to her hair to make sure it wasn’t a dream. “Disgraceful!”
muttered the old man more to himself than to her. “Common, vulgar
fellows! I am afraid they disturbed you, gracious Fräulein, blundering
in here like that.” No, not really. She was just going to wake up, and
she took out silver watch to look at the time. Half-past four. A cold
blue light filled the window panes. Now when she rubbed a place
she could see bright patches of fields, a clump of white houses like
mushrooms, a road “like a picture” with poplar trees on either side, a
thread of river. How pretty it was! How pretty and how different!
Even those pink clouds in the sky looked foreign. It was cold, but
she pretended that it was far colder and rubbed her hands together
and shivered, pulling at the collar of her coat because she was so
happy.
The train began to slow down. The engine gave a long shrill
whistle. They were coming to a town. Taller houses, pink and yellow,
glided by, fast asleep behind their green eyelids, and guarded by the
poplar trees that quivered in the blue air as if on tiptoe, listening. In
one house a woman opened the shutters, flung a red and white
mattress across the window frame and stood staring at the train. A
pale woman with black hair and a white woollen shawl over her
shoulders. More women appeared at the doors and at the windows
of the sleeping houses. There came a flock of sheep. The shepherd
wore a blue blouse and pointed wooden shoes. Look! look what
flowers—and by the railway station too! Standard roses like
bridesmaids’ bouquets, white geraniums, waxy pink ones that you
would never see out of a greenhouse at home. Slower and slower. A
man with a watering-can was spraying the platform. “A-a-a-ah!”
Somebody came running and waving his arms. A huge fat woman
waddled through the glass doors of the station with a tray of
strawberries. Oh, she was thirsty! She was very thirsty! “A-a-a-ah!”
The same somebody ran back again. The train stopped.
The old man pulled his coat round him and got up, smiling at her.
He murmured something she didn’t quite catch, but she smiled back
at him as he left the carriage. While he was away the little governess
looked at herself again in the glass, shook and patted herself with
the precise practical care of a girl who is old enough to travel by
herself and has nobody else to assure her that she is “quite all right
behind.” Thirsty and thirsty! The air tasted of water. She let down
the window and the fat woman with the strawberries passed as if on
purpose; holding up the tray to her. “Nein, danke,” said the little
governess, looking at the big berries on their gleaming leaves. “Wie
viel?” she asked as the fat woman moved away. “Two marks fifty,
Fräulein.” “Good gracious!” She came in from the window and sat
down in the corner, very sobered for a minute. Half a crown! “H-o-o-
o-o-o-e-e-e!” shrieked the train, gathering itself together to be off
again. She hoped the old man wouldn’t be left behind. Oh, it was
daylight—everything was lovely if only she hadn’t been so thirsty.
Where was the old man—oh, here he was—she dimpled at him as
though he were an old accepted friend as he closed the door and,
turning, took from under his cape a basket of the strawberries. “If
Fräulein would honour me by accepting these . . .” “What for me?”
But she drew back and raised her hands as though he were about to
put a wild little kitten on her lap.
“Certainly, for you,” said the old man. “For myself it is twenty
years since I was brave enough to eat strawberries.” “Oh, thank you
very much. Danke bestens,” she stammered, “sie sind so sehr
schön!” “Eat them and see,” said the old man looking pleased and
friendly. “You won’t have even one?” “No, no, no.” Timidly and
charmingly her hand hovered. They were so big and juicy she had to
take two bites to them—the juice ran all down her fingers—and it
was while she munched the berries that she first thought of the old
man as a grandfather. What a perfect grandfather he would make!
Just like one out of a book!
The sun came out, the pink clouds in the sky, the strawberry
clouds were eaten by the blue. “Are they good?” asked the old man.
“As good as they look?”
When she had eaten them she felt she had known him for years.
She told him about Frau Arnholdt and how she had got the place.
Did he know the Hotel Grunewald? Frau Arnholdt would not arrive
until the evening. He listened, listened until he knew as much about
the affair as she did, until he said—not looking at her—but
smoothing the palms of his brown suède gloves together: “I wonder
if you would let me show you a little of Munich to-day. Nothing much
—but just perhaps a picture gallery and the Englischer Garten. It
seems such a pity that you should have to spend the day at the
hotel, and also a little uncomfortable . . . in a strange place. Nicht
wahr? You would be back there by the early afternoon or whenever
you wish, of course, and you would give an old man a great deal of
pleasure.”
It was not until long after she had said “Yes”—because the
moment she had said it and he had thanked her he began telling her
about his travels in Turkey and attar of roses—that she wondered
whether she had done wrong. After all, she really did not know him.
But he was so old and he had been so very kind—not to mention the
strawberries. . . . And she couldn’t have explained the reason why
she said “No,” and it was her last day in a way, her last day to really
enjoy herself in. “Was I wrong? Was I?” A drop of sunlight fell into
her hands and lay there, warm and quivering. “If I might accompany
you as far as the hotel,” he suggested, “and call for you again at
about ten o’clock.” He took out his pocket-book and handed her a
card. “Herr Regierungsrat. . . .” He had a title! Well, it was bound to
be all right! So after that the little governess gave herself up to the
excitement of being really abroad, to looking out and reading the
foreign advertisement signs, to being told about the places they
came to—having her attention and enjoyment looked after by the
charming old grandfather—until they reached Munich and the
Hauptbahnhof. “Porter! Porter!” He found her a porter, disposed of
his own luggage in a few words, guided her through the bewildering
crowd out of the station down the clean white steps into the white
road to the hotel. He explained who she was to the manager as
though all this had been bound to happen, and then for one moment
her little hand lost itself in the big brown suède ones. “I will call for
you at ten o’clock.” He was gone.
“This way, Fräulein,” said a waiter, who had been dodging behind
the manager’s back, all eyes and ears for the strange couple. She
followed him up two flights of stairs into a dark bedroom. He dashed
down her dress-basket and pulled up a clattering, dusty blind. Ugh!
what an ugly, cold room—what enormous furniture! Fancy spending
the day in here! “Is this the room Frau Arnholdt ordered?” asked the
little governess. The waiter had a curious way of staring as if there
was something funny about her. He pursed up his lips about to
whistle, and then changed his mind. “Gewiss,” he said. Well, why
didn’t he go? Why did he stare so? “Gehen Sie,” said the little
governess, with frigid English simplicity. His little eyes, like currants,
nearly popped out of his doughy cheeks. “Gehen Sie sofort,” she
repeated icily. At the door he turned. “And the gentleman,” said he,
“shall I show the gentleman upstairs when he comes?”
Over the white streets big white clouds fringed with silver—and
sunshine everywhere. Fat, fat coachmen driving fat cabs; funny
women with little round hats cleaning the tramway lines; people
laughing and pushing against one another; trees on both sides of
the streets and everywhere you looked almost, immense fountains;
a noise of laughing from the footpaths or the middle of the streets or
the open windows. And beside her, more beautifully brushed than
ever, with a rolled umbrella in one hand and yellow gloves instead of
brown ones, her grandfather who had asked her to spend the day.
She wanted to run, she wanted to hang on his arm, she wanted to
cry every minute, “Oh, I am so frightfully happy!” He guided her
across the roads, stood still while she “looked,” and his kind eyes
beamed on her and he said “just whatever you wish.” She ate two
white sausages and two little rolls of fresh bread at eleven o’clock in
the morning and she drank some beer, which he told her wasn’t
intoxicating, wasn’t at all like English beer, out of a glass like a
flower vase. And then they took a cab and really she must have seen
thousands and thousands of wonderful classical pictures in about a
quarter of an hour! “I shall have to think them over when I am
alone.” . . . But when they came out of the picture gallery it was
raining. The grandfather unfurled his umbrella and held it over the
little governess. They started to walk to the restaurant for lunch.
She, very close beside him so that he should have some of the
umbrella, too. “It goes easier,” he remarked in a detached way, “if
you take my arm, Fräulein. And besides it is the custom in Germany.”
So she took his arm and walked beside him while he pointed out the
famous statues, so interested that he quite forgot to put down the
umbrella even when the rain was long over.
After lunch they went to a café to hear a gipsy band, but she did
not like that at all. Ugh! such horrible men where there with heads
like eggs and cuts on their faces, so she turned her chair and
cupped her burning cheeks in her hands and watched her old friend
instead. . . . Then they went to the Englischer Garten.
“I wonder what the time is,” asked the little governess. “My watch
has stopped. I forgot to wind it in the train last night. We’ve seen
such a lot of things that I feel it must be quite late.” “Late!” He
stopped in front of her laughing and shaking his head in a way she
had begun to know. “Then you have not really enjoyed yourself.
Late! Why, we have not had any ice cream yet!” “Oh, but I have
enjoyed myself,” she cried, distressed, “more than I can possibly say.
It has been wonderful! Only Frau Arnholdt is to be at the hotel at six
and I ought to be there by five.” “So you shall. After the ice cream I
shall put you into a cab and you can go there comfortably.” She was
happy again. The chocolate ice cream melted—melted in little sips a
long way down. The shadows of the trees danced on the table
cloths, and she sat with her back safely turned to the ornamental
clock that pointed to twenty-five minutes to seven. “Really and truly,”
said the little governess earnestly, “this has been the happiest day of
my life. I’ve never even imagined such a day.” In spite of the ice
cream her grateful baby heart glowed with love for the fairy
grandfather.
So they walked out of the garden down a long alley. The day was
nearly over. “You see those big buildings opposite,” said the old man.
“The third storey—that is where I live. I and the old housekeeper
who looks after me.” She was very interested. “Now just before I
find a cab for you, will you come and see my little ‘home’ and let me
give you a bottle of the attar of roses I told you about in the train?
For remembrance?” She would love to. “I’ve never seen a bachelor’s
flat in my life,” laughed the little governess.
The passage was quite dark. “Ah, I suppose my old woman has
gone out to buy me a chicken. One moment.” He opened a door and
stood aside for her to pass, a little shy but curious, into a strange
room. She did not know quite what to say. It wasn’t pretty. In a way
it was very ugly—but neat, and, she supposed, comfortable for such
an old man. “Well, what do you think of it?” He knelt down and took
from a cupboard a round tray with two pink glasses and a tall pink
bottle. “Two little bedrooms beyond,” he said gaily, “and a kitchen.
It’s enough, eh?” “Oh, quite enough.” “And if ever you should be in
Munich and care to spend a day or two—why there is always a little
nest—a wing of a chicken, and a salad, and an old man delighted to
be your host once more and many many times, dear little Fräulein!”
He took the stopper out of the bottle and poured some wine into the
two pink glasses. His hand shook and the wine spilled over the tray.
It was very quiet in the room. She said: “I think I ought to go now.”
“But you will have a tiny glass of wine with me—just one before you
go?” said the old man. “No, really no. I never drink wine. I—I have
promised never to touch wine or anything like that.” And though he
pleaded and though she felt dreadfully rude, especially when he
seemed to take it to heart so, she was quite determined. “No, really,
please.” “Well, will you just sit down on the sofa for five minutes and
let me drink your health?” The little governess sat down on the edge
of the red velvet couch and he sat down beside her and drank her
health at a gulp. “Have you really been happy to-day?” asked the old
man, turning round, so close beside her that she felt his knee
twitching against hers. Before she could answer he held her hands.
“And are you going to give me one little kiss before you go?” he
asked, drawing her closer still.
It was a dream! It wasn’t true! It wasn’t the same old man at all.
Ah, how horrible! The little governess stared at him in terror. “No,
no, no!” she stammered, struggling out of his hands. “One little kiss.
A kiss. What is it? Just a kiss, dear little Fräulein. A kiss.” He pushed
his face forward, his lips smiling broadly; and how his little blue eyes
gleamed behind the spectacles! “Never—never. How can you!” She
sprang up, but he was too quick and he held her against the wall,
pressed against her his hard old body and his twitching knee and,
though she shook her head from side to side, distracted, kissed her
on the mouth. On the mouth! Where not a soul who wasn’t a near
relation had ever kissed her before. . . .
She ran, ran down the street until she found a broad road with
tram lines and a policeman standing in the middle like a clockwork
doll. “I want to get a tram to the Hauptbahnhof,” sobbed the little
governess. “Fräulein?” She wrung her hands at him. “The
Hauptbahnhof. There—there’s one now,” and while he watched very
much surprised, the little girl with her hat on one side, crying
without a handkerchief, sprang on to the tram—not seeing the
conductor’s eyebrows, nor hearing the hochwohlgebildete Dame
talking her over with a scandalized friend. She rocked herself and
cried out loud and said “Ah, ah!” pressing her hands to her mouth.
“She has been to the dentist,” shrilled a fat old woman, too stupid to
be uncharitable. “Na, sagen Sie ’mal, what toothache! The child
hasn’t one left in her mouth.” While the tram swung and jangled
through a world full of old men with twitching knees.
When the little governess reached the hall of the Hotel Grunewald
the same waiter who had come into her room in the morning was
standing by table, polishing a tray of glasses. The sight of the little
governess seemed to fill him out with some inexplicable important
content. He was ready for her question; his answer came pat and
suave. “Yes, Fräulein, the lady has been here. I told her that you
had arrived and gone out again immediately with a gentleman. She
asked me when you were coming back again—but of course I could
not say. And then she went to the manager.” He took up a glass from
the table, held it up to the light, looked at it with one eye closed,
and started polishing it with a corner of his apron. “. . . ?” “Pardon,
Fräulein? Ach, no, Fräulein. The manager could tell her nothing—
nothing.” He shook his head and smiled at the brilliant glass. “Where
is the lady now?” asked the little governess, shuddering so violently
that she had to hold her handkerchief up to her mouth. “How should
I know?” cried the waiter, and as he swooped past her to pounce
upon a new arrival his heart beat so hard against his ribs that he
nearly chuckled aloud. “That’s it! that’s it!” he thought. “That will
show her.” And as he swung the new arrival’s box on to his shoulders
—hoop!—as though he were a giant and the box a feather, he
minced over again the little governess’s words, “Gehen Sie. Gehen
Sie sofort. Shall I! Shall I!” he shouted to himself.
Revelations
From eight o’clock in the morning until about half-past eleven
Monica Tyrell suffered from her nerves, and suffered so terribly that
these hours were—agonizing, simply. It was not as though she could
control them. “Perhaps if I were ten years younger . . .” she would
say. For now that she was thirty-three she had queer little way of
referring to her age on all occasions, of looking at her friends with
grave, childish eyes and saying: “Yes, I remember how twenty years
ago . . .” or of drawing Ralph’s attention to the girls—real girls—with
lovely youthful arms and throats and swift hesitating movements
who sat near them in restaurants. “Perhaps if I were ten years
younger . . .”
“Why don’t you get Marie to sit outside your door and absolutely
forbid anybody to come near your room until you ring your bell?”
“Oh, if it were as simple as that!” She threw her little gloves down
and pressed her eyelids with her fingers in the way he knew so well.
“But in the first place I’d be so conscious of Marie sitting there,
Marie shaking her finger at Rudd and Mrs. Moon, Marie as a kind of
cross between a wardress and a nurse for mental cases! And then,
there’s the post. One can’t get over the fact that the post comes,
and once it has come, who—who—could wait until eleven for the
letters?”
His eyes grew bright; he quickly, lightly clasped her. “My letters,
darling?”
“Perhaps,” she drawled, softly, and she drew her hand over his
reddish hair, smiling too, but thinking: “Heavens! What a stupid thing
to say!”
But this morning she had been awakened by one great slam of the
front door. Bang. The flat shook. What was it? She jerked up in bed,
clutching the eiderdown; her heart beat. What could it be? Then she
heard voices in the passage. Marie knocked, and, as the door
opened, with a sharp tearing rip out flew the blind and the curtains,
stiffening, flapping, jerking. The tassel of the blind knocked—
knocked against the window. “Eh-h, voilà!” cried Marie, setting down
the tray and running. “C’est le vent, Madame. C’est un vent
insupportable.”
Up rolled the blind; the window went up with a jerk; a whitey-
greyish light filled the room. Monica caught a glimpse of a huge pale
sky and a cloud like a torn shirt dragging across before she hid her
eyes with her sleeve.
“Marie! the curtains! Quick, the curtains!” Monica fell back into the
bed and then “Ring-ting-a-ping-ping, ring-ting-a-ping-ping.” It was
the telephone. The limit of her suffering was reached; she grew
quite calm. “Go and see, Marie.”
“It is Monsieur. To know if Madame will lunch at Princes’ at one-
thirty to-day.” Yes, it was Monsieur himself. Yes, he had asked that
the message be given to Madame immediately. Instead of replying,
Monica put her cup down and asked Marie in a small wondering
voice what time it was. It was half-past nine. She lay still and half
closed her eyes. “Tell Monsieur I cannot come,” she said gently. But
as the door shut, anger—anger suddenly gripped her close, close,
violent, half strangling her. How dared he? How dared Ralph do such
a thing when he knew how agonizing her nerves were in the
morning! Hadn’t she explained and described and even—though
lightly, of course; she couldn’t say such a thing directly—given him
to understand that this was the one unforgivable thing.
And then to choose this frightful windy morning. Did he think it
was just a fad of hers, a little feminine folly to be laughed at and
tossed aside? Why, only last night she had said: “Ah, but you must
take me seriously, too.” And he had replied: “My darling, you’ll not
believe me, but I know you infinitely better than you know yourself.
Every delicate thought and feeling I bow to, I treasure. Yes, laugh! I
love the way your lip lifts”—and he had leaned across the table—“I
don’t care who sees that I adore all of you. I’d be with you on
mountain-top and have all the searchlights of the world play upon
us.”
“Heavens!” Monica almost clutched her head. Was it possible he
had really said that? How incredible men were! And she had loved
him—how could she have loved a man who talked like that. What
had she been doing ever since that dinner party months ago, when
he had seen her home and asked if he might come and “see again
that slow Arabian smile”? Oh, what nonsense—what utter nonsense
—and yet she remembered at the time a strange deep thrill unlike
anything she had ever felt before.
“Coal! Coal! Coal! Old iron! Old iron! Old iron!” sounded from
below. It was all over. Understand her? He had understood nothing.
That ringing her up on a windy morning was immensely significant.
Would he understand that? She could almost have laughed. “You
rang me up when the person who understood me simply couldn’t
have.” It was the end. And when Marie said: “Monsieur replied he
would be in the vestibule in case Madame changed her mind,”
Monica said: “No, not verbena, Marie. Carnations. Two handfuls.”
A wild white morning, a tearing, rocking wind. Monica sat down
before the mirror. She was pale. The maid combed back her dark
hair—combed it all back—and her face was like a mask, with pointed
eyelids and dark red lips. As she stared at herself in the blueish
shadowy glass she suddenly felt—oh, the strangest, most
tremendous excitement filling her slowly, slowly, until she wanted to
fling out her arms, to laugh, to scatter everything, to shock Marie, to
cry: “I’m free. I’m free. I’m free as the wind.” And now all this
vibrating, trembling, exciting, flying world was hers. It was her
kingdom. No, no, she belonged to nobody but Life.
“That will do, Marie,” she stammered. “My hat, my coat, my bag.
And now get me a taxi.” Where was she going? Oh, anywhere. She
could not stand this silent flat, noiseless Marie, this ghostly, quiet,
feminine interior. She must be out; she must be driving quickly—
anywhere, anywhere.
“The taxi is there, Madame.” As she pressed open the big outer
doors of the flats the wild wind caught her and floated her across
the pavement. Where to? She got in, and smiling radiantly at the
cross, cold-looking driver, she told him to take her to her
hairdresser’s. What would she have done without her hairdresser?
Whenever Monica had nowhere else to go to or nothing on earth to
do she drove there. She might just have her hair waved, and by that
time she’d have thought out a plan. The cross, cold driver drove at a
tremendous pace, and she let herself be hurled from side to side.
She wished he would go faster and faster. Oh, to be free of Princes’
at one-thirty, of being the tiny kitten in the swansdown basket, of
being the Arabian, and the grave, delighted child and the little wild
creature. . . . “Never again,” she cried aloud, clenching her small fist.
But the cab had stopped, and the driver was standing holding the
door open for her.
The hairdresser’s shop was warm and glittering. It smelled of soap
and burnt paper and wallflower brilliantine. There was Madame
behind the counter, round, fat, white, her head like a powder-puff
rolling on a black satin pin-cushion. Monica always had the feeling
that they loved her in this shop and understood her—the real her—
far better than many of her friends did. She was her real self here,
and she and Madame had often talked—quite strangely—together.
Then there was George who did her hair, young, dark, slender
George. She was really fond of him.
But to-day—how curious! Madame hardly greeted her. Her face
was whiter than ever, but rims of bright red showed round her blue
bead eyes, and even the rings on her pudgy fingers did not flash.
They were cold, dead, like chips of glass. When she called through
the wall-telephone to George there was a note in her voice that had
never been there before. But Monica would not believe this. No, she
refused to. It was just her imagination. She sniffed greedily the
warm, scented air, and passed behind the velvet curtain into the
small cubicle.
Her hat and jacket were off and hanging from the peg, and still
George did not come. This was the first time he had ever not been
there to hold the chair for her, to take her hat and hang up her bag,
dangling it in his fingers as though it were something he’d never
seen before—something fairy. And how quiet the shop was! There
was not a sound even from Madame. Only the wind blew, shaking
the old house; the wind hooted, and the portraits of Ladies of the
Pompadour Period looked down and smiled, cunning and sly. Monica
wished she hadn’t come. Oh, what a mistake to have come! Fatal.
Fatal. Where was George? If he didn’t appear the next moment she
would go away. She took off the white kimono. She didn’t want to
look at herself any more. When she opened a big pot of cream on
the glass shelf her fingers trembled. There was a tugging feeling at
her heart as though her happiness—her marvellous happiness—were
trying to get free.
“I’ll go. I’ll not stay.” She took down her hat. But just at that
moment steps sounded, and, looking in the mirror, she saw George
bowing in the doorway. How queerly he smiled! It was the mirror of
course. She turned round quickly. His lips curled back in a sort of
grin, and—wasn’t he unshaved?—he looked almost green in the
face.
“Very sorry to have kept you waiting,” he mumbled, sliding, gliding
forward.
Oh, no, she wasn’t going to stay. “I’m afraid,” she began. But he
had lighted the gas and laid the tongs across, and was holding out
the kimono.
“It’s a wind,” he said. Monica submitted. She smelled his fresh
young fingers pinning the jacket under her chin. “Yes, there is a
wind,” said she, sinking back into the chair. And silence fell. George
took out the pins in his expert way. Her hair tumbled back, but he
didn’t hold it as he usually did, as though to feel how fine and soft
and heavy it was. He didn’t say it “was in a lovely condition.” He let
it fall, and, taking a brush out of a drawer, he coughed faintly,
cleared his throat and said dully: “Yes, it’s a pretty strong one, I
should say it was.”
She had no reply to make. The brush fell on her hair. Oh, oh, how
mournful, how mournful! It fell quick and light, it fell like leaves; and
then it fell heavy, tugging like the tugging at her heart. “That’s
enough,” she cried, shaking herself free.
“Did I do it too much?” asked George. He crouched over the
tongs. “I’m sorry.” There came the smell of burnt paper—the smell
she loved—and he swung the hot tongs round in his hand, staring
before him. “I shouldn’t be surprised if it rained.” He took up a piece
of her hair, when—she couldn’t bear it any longer—she stopped him.
She looked at him; she saw herself looking at him in the white
kimono like a nun. “Is there something the matter here? Has
something happened?” But George gave a half shrug and a grimace.
“Oh, no, Madame. Just a little occurrence.” And he took up the piece
of hair again. But, oh, she wasn’t deceived. That was it. Something
awful had happened. The silence—really, the silence seemed to
come drifting down like flakes of snow. She shivered. It was cold in
the little cubicle, all cold and glittering. The nickel taps and jets and
sprays looked somehow almost malignant. The wind rattled the
window-frame; a piece of iron banged, and the young man went on
changing the tongs, crouching over her. Oh, how terrifying Life was,
thought Monica. How dreadful. It is the loneliness which is so
appalling. We whirl along like leaves, and nobody knows—nobody
cares where we fall, in what black river we float away. The tugging
feeling seemed to rise into her throat. It ached, ached; she longed
to cry. “That will do,” she whispered. “Give me the pins.” As he stood
beside her, so submissive, so silent, she nearly dropped her arms
and sobbed. She couldn’t bear any more. Like a wooden man the
gay young George still slid, glided, handed her her hat and veil, took
the note, and brought back the change. She stuffed it into her bag.
Where was she going now?
George took a brush. “There is a little powder on your coat,” he
murmured. He brushed it away. And then suddenly he raised himself
and, looking at Monica, gave a strange wave with the brush and
said: “The truth is, Madame, since you are an old customer—my
little daughter died this morning. A first child”—and then his white
face crumpled like paper, and he turned his back on her and began
brushing the cotton kimono. “Oh, oh,” Monica began to cry. She ran
out of the shop into the taxi. The driver, looking furious, swung off
the seat and slammed the door again. “Where to?”
“Princes’,” she sobbed. And all the way there she saw nothing but
a tiny wax doll with a feather of gold hair, lying meek, its tiny hands
and feet crossed. And then just before she came to Princes’ she saw
a flower shop full of white flowers. Oh, what a perfect thought.
Lilies-of-the-valley, and white pansies, double white violets and white
velvet ribbon. . . . From an unknown friend. . . . From one who
understands. . . . For a Little Girl. . . . She tapped against the
window, but the driver did not hear; and, anyway, they were at
Princes’ already.
The Escape
It was his fault, wholly and solely his fault, that they had missed
the train. What if the idiotic hotel people had refused to produce the
bill? Wasn’t that simply because he hadn’t impressed upon the
waiter at lunch that they must have it by two o’clock? Any other man
would have sat there and refused to move until they handed it over.
But no! His exquisite belief in human nature had allowed him to get
up and expect one of those idiots to bring it to their room. . . . And
then, when the voiture did arrive, while they were still (Oh,
Heavens!) waiting for change, why hadn’t he seen to the
arrangement of the boxes so that they could, at least, have started
the moment the money had come? Had he expected her to go
outside, to stand under the awning in the heat and point with her
parasol? Very amusing picture of English domestic life. Even when
the driver had been told how fast he had to drive he had paid no
attention whatsoever—just smiled. “Oh,” she groaned, “if she’d been
a driver she couldn’t have stopped smiling herself at the absurd,
ridiculous way he was urged to hurry.” And she sat back and imitated
his voice: “Allez, vite, vite”—and begged the driver’s pardon for
troubling him. . . .
And then the station—unforgettable—with the sight of the jaunty
little train shuffling away and those hideous children waving from the
windows. “Oh, why am I made to bear these things? Why am I
exposed to them? . . .” The glare, the flies, while they waited, and
he and the stationmaster put their heads together over the time-
table, trying to find this other train, which, of course, they wouldn’t
catch. The people who’d gathered round, and the woman who’d held
up that baby with that awful, awful head. . . . “Oh, to care as I care
—to feel as I feel, and never to be saved anything—never to know
for one moment what it was to . . . to . . .”
Her voice had changed. It was shaking now—crying now. She
fumbled with her bag, and produced from its little maw a scented
handkerchief. She put up her veil and, as though she were doing it
for somebody else, pitifully, as though she were saying to somebody
else: “I know, my darling,” she pressed the handkerchief to her eyes.
The little bag, with its shiny, silvery jaws open, lay on her lap. He
could see her powder-puff, her rouge stick, a bundle of letters, a
phial of tiny black pills like seeds, a broken cigarette, a mirror, white
ivory tablets with lists on them that had been heavily scored
through. He thought: “In Egypt she would be buried with those
things.”
They had left the last of the houses, those small straggling houses
with bits of broken pot flung among the flower-beds and half-naked
hens scratching round the doorsteps. Now they were mounting a
long steep road that wound round the hill and over into the next
bay. The horses stumbled, pulling hard. Every five minutes, every
two minutes the driver trailed the whip across them. His stout back
was solid as wood; there were boils on his reddish neck, and he
wore a new, a shining new straw hat. . . .
There was a little wind, just enough wind to blow to satin the new
leaves on the fruit trees, to stroke the fine grass, to turn to silver the
smoky olives—just enough wind to start in front of the carriage a
whirling, twirling snatch of dust that settled on their clothes like the
finest ash. When she took out her powder-puff the powder came
flying over them both.
“Oh, the dust,” she breathed, “the disgusting, revolting dust.” And
she put down her veil and lay back as if overcome.
“Why don’t you put up your parasol?” he suggested. It was on the
front seat, and he leaned forward to hand it to her. At that she
suddenly sat upright and blazed again.
“Please leave my parasol alone! I don’t want my parasol! And
anyone who was not utterly insensitive would know that I’m far, far
too exhausted to hold up a parasol. And with a wind like this tugging
at it. . . . Put it down at once,” she flashed, and then snatched the
parasol from him, tossed it into the crumpled hood behind, and
subsided, panting.
Another bend of the road, and down the hill there came a troop of
little children, shrieking and giggling, little girls with sun-bleached
hair, little boys in faded soldiers’ caps. In their hands they carried
flowers—any kind of flowers—grabbed by the head, and these they
offered, running beside the carriage. Lilac, faded lilac, greeny-white
snowballs, one arum lily, a handful of hyacinths. They thrust the
flowers and their impish faces into the carriage; one even threw into
her lap a bunch of marigolds. Poor little mice! He had his hand in his
trouser pocket before her. “For Heaven’s sake don’t give them
anything. Oh, how typical of you! Horrid little monkeys! Now they’ll
follow us all the way. Don’t encourage them; you would encourage
beggars”; and she hurled the bunch out of the carriage with, “Well,
do it when I’m not there, please.”
He saw the queer shock on the children’s faces. They stopped
running, lagged behind, and then they began to shout something,
and went on shouting until the carriage had rounded yet another
bend.
“Oh, how many more are there before the top of the hill is
reached? The horses haven’t trotted once. Surely it isn’t necessary
for them to walk the whole way.”
“We shall be there in a minute now,” he said, and took out his
cigarette-case. At that she turned round towards him. She clasped
her hands and held them against her breast; her dark eyes looked
immense, imploring, behind her veil; her nostrils quivered, she bit
her lip, and her head shook with a little nervous spasm. But when
she spoke, her voice was quite weak and very, very calm.
“I want to ask you something. I want to beg something of you,”
she said. “I’ve asked you hundreds and hundreds of times before,
but you’ve forgotten. It’s such a little thing, but if you knew what it
meant to me. . . .” She pressed her hands together. “But you can’t
know. No human creature could know and be so cruel.” And then,
slowly, deliberately, gazing at him with those huge, sombre eyes: “I
beg and implore you for the last time that when we are driving
together you won’t smoke. If you could imagine,” she said, “the
anguish I suffer when that smoke comes floating across my face. . .
.”
“Very well,” he said. “I won’t. I forgot.” And he put the case back.
“Oh, no,” said she, and almost began to laugh, and put the back
of her hand across her eyes. “You couldn’t have forgotten. Not that.”
The wind came, blowing stronger. They were at the top of the hill.
“Hoy-yip-yip-yip,” cried the driver. They swung down the road that
fell into a small valley, skirted the sea coast at the bottom of it, and
then coiled over a gentle ridge on the other side. Now there were
houses again, blue-shuttered against the heat, with bright burning
gardens, with geranium carpets flung over the pinkish walls. The
coast-line was dark; on the edge of the sea a white silky fringe just
stirred. The carriage swung down the hill, bumped, shook. “Yi-ip,”
shouted the driver. She clutched the sides of the seat, she closed her
eyes, and he knew she felt this was happening on purpose; this
swinging and bumping, this was all done—and he was responsible
for it, somehow—to spite her because she had asked if they couldn’t
go a little faster. But just as they reached the bottom of the valley
there was one tremendous lurch. The carriage nearly overturned,
and he saw her eyes blaze at him, and she positively hissed, “I
suppose you are enjoying this?”
They went on. They reached the bottom of the valley. Suddenly
she stood up. “Cocher! Cocher! Arrêtez-vous!” She turned round and
looked into the crumpled hood behind. “I knew it,” she exclaimed. “I
knew it. I heard it fall, and so did you, at that last bump.”
“What? Where?”
“My parasol. It’s gone. The parasol that belonged to my mother.
The parasol that I prize more than—more than . . .” She was simply
beside herself. The driver turned round, his gay, broad face smiling.
“I, too, heard something,” said he, simply and gaily. “But I thought
as Monsieur and Madame said nothing . . .”
“There. You hear that. Then you must have heard it too. So that
accounts for the extraordinary smile on your face. . . .”
“Look here,” he said, “it can’t be gone. If it fell out it will be there
still. Stay where you are. I’ll fetch it.”
But she saw through that. Oh, how she saw through it! “No, thank
you.” And she bent her spiteful, smiling eyes upon him, regardless of
the driver. “I’ll go myself. I’ll walk back and find it, and trust you not
to follow. For”—knowing the driver did not understand, she spoke
softly, gently—“if I don’t escape from you for a minute I shall go
mad.”
She stepped out of the carriage. “My bag.” He handed it to her.
“Madame prefers . . .”
But the driver had already swung down from his seat, and was
seated on the parapet reading a small newspaper. The horses stood
with hanging heads. It was still. The man in the carriage stretched
himself out, folded his arms. He felt the sun beat on his knees. His
head was sunk on his breast. “Hish, hish,” sounded from the sea.
The wind sighed in the valley and was quiet. He felt himself, lying
there, a hollow man, a parched, withered man, as it were, of ashes.
And the sea sounded, “Hish, hish.”
It was then that he saw the tree, that he was conscious of its
presence just inside a garden gate. It was an immense tree with a
round, thick silver stem and a great arc of copper leaves that gave
back the light and yet were sombre. There was something beyond
the tree—a whiteness, a softness, an opaque mass, half-hidden—
with delicate pillars. As he looked at the tree he felt his breathing die
away and he became part of the silence. It seemed to grow, it
seemed to expand in the quivering heat until the great carved leaves
hid the sky, and yet it was motionless. Then from within its depths
or from beyond there came the sound of a woman’s voice. A woman
was singing. The warm untroubled voice floated upon the air, and it
was all part of the silence as he was part of it. Suddenly, as the
voice rose, soft, dreaming, gentle, he knew that it would come
floating to him from the hidden leaves and his peace was shattered.
What was happening to him? Something stirred in his breast.
Something dark, something unbearable and dreadful pushed in his
bosom, and like a great weed it floated, rocked . . . it was warm,
stifling. He tried to struggle to tear at it, and at the same moment—
all was over. Deep, deep, he sank into the silence, staring at the tree
and waiting for the voice that came floating, falling, until he felt
himself enfolded.
. . . . .
In the shaking corridor of the train. It was night. The train rushed
and roared through the dark. He held on with both hands to the
brass rail. The door of their carriage was open.
“Do not disturb yourself, Monsieur. He will come in and sit down
when he wants to. He likes—he likes—it is his habit. . . . Oui,
Madame, je suis un peu souffrante. . . . Mes nerfs. Oh, but my
husband is never so happy as when he is travelling. He likes
roughing it. . . . My husband. . . . My husband. . . .”
The voices murmured, murmured. They were never still. But so
great was his heavenly happiness as he stood there he wished he
might live for ever.
Transcriber’s Note
Images of the source text used in this transcription are available
through the Internet Archive.
The following changes to the text were noted:
p. 2: Two subdued chirrups: “Thank you, Mrs. Samuel Josephs”—
Added a period after “Josephs”.
p. 3: The buggy tiwnkled away in the sunlight—Changed
“tiwnkled” to “twinkled”.
p. 14: lifted up his oat tails.—Changed “oat” to “coat”.
p. 101: the garçon was hauing up the boxes—Changed “hauing”
to "hauling".
p. 169: I have sung that music many times.”—Inserted a closing
single quotation mark before the closing double quotation mark.
p. 154: It doesn’t matter at all, darling.” said the good friend.—
Changed period after “darling” to a comma.
p. 187: “That,” she said, “is most becoming,”—Comma after
“becoming” changed to a period.
p. 190: opening the French window to let Klaymongso into the
garden, cries.—Changed the period after “cries” to a colon.
p. 201: What a genius Mr Peacock was.—Inserted a period after
“Mr”.
p. 202: There she was—off again Now she—Inserted a period
after “again”.
p. 210: “That's where the ice pudding is to be,” said Cook—Added
a period to the end of the sentence.
p. 215: “I’m hanged if I won’t,” cried Father. I won’t—Inserted an
opening double quotation mark between “Father.” and “I won’t”.
p. 258: “I think I ought to gonow.”—Divided “gonow” into two
words.
*** END OF THE PROJECT GUTENBERG EBOOK BLISS, AND OTHER
STORIES ***
Updated editions will replace the previous one—the old editions will
be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.
START: FULL LICENSE
THE FULL PROJECT GUTENBERG LICENSE
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Object-Oriented Python 1st Edition Irv Kalb
PDF
Object-Oriented Python 1st Edition Irv Kalb
PDF
Object-Oriented Python 1st Edition Irv Kalb
PDF
Download full ebook of Object-Oriented Python Irv Kalb instant download pdf
PDF
Selenium training-course-content-syllabus-credo systemz
PDF
Android Programming For Developers John Horton Helder Vasconcelos
PDF
Dead Simple Python Idiomatic Python for the Impatient Programmer Jason C. Mcd...
PDF
Dead Simple Python Idiomatic Python for the Impatient Programmer Jason C. Mcd...
Object-Oriented Python 1st Edition Irv Kalb
Object-Oriented Python 1st Edition Irv Kalb
Object-Oriented Python 1st Edition Irv Kalb
Download full ebook of Object-Oriented Python Irv Kalb instant download pdf
Selenium training-course-content-syllabus-credo systemz
Android Programming For Developers John Horton Helder Vasconcelos
Dead Simple Python Idiomatic Python for the Impatient Programmer Jason C. Mcd...
Dead Simple Python Idiomatic Python for the Impatient Programmer Jason C. Mcd...

Similar to Objectoriented Python 1st Edition Irv Kalb (20)

PPTX
[GEMINI EXTERNAL DECK] Introduction to Gemini.pptx
PDF
Learn To Code Like A Professional With Pythonan Open Source Versatile And Pow...
PDF
Selenium training12 1
PDF
Selenium training12 1
PDF
Selenium training-course-content
DOCX
python training.docx
PPTX
Code camp 2011 Getting Started with IOS, Una Daly
PPT
JAX 08 - Agile RCP
PDF
Pytorch A Detailed Overview Agladze Mikhail
PDF
Programming Python 3rd ed Edition Mark Lutz
PPTX
Build 2019 Recap
PDF
QR Code Generator.pdf
PDF
Learn Google Flutter Fast: 65 Example Apps Mark Clow
PPTX
Django Framework Overview forNon-Python Developers
PDF
Instant download Architecture Patterns with Python 1st Edition Harry Percival...
PPTX
Full_Stack_Dule_1.NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN[1].pptx
PPT
2 Day - WPF Training by Adil Mughal
PDF
Function Calling with the Vertex AI Gemini API
PDF
mlflow: Accelerating the End-to-End ML lifecycle
PPTX
313534882-Modular-Programming-with-Python-Sample-Chapter.pptx
[GEMINI EXTERNAL DECK] Introduction to Gemini.pptx
Learn To Code Like A Professional With Pythonan Open Source Versatile And Pow...
Selenium training12 1
Selenium training12 1
Selenium training-course-content
python training.docx
Code camp 2011 Getting Started with IOS, Una Daly
JAX 08 - Agile RCP
Pytorch A Detailed Overview Agladze Mikhail
Programming Python 3rd ed Edition Mark Lutz
Build 2019 Recap
QR Code Generator.pdf
Learn Google Flutter Fast: 65 Example Apps Mark Clow
Django Framework Overview forNon-Python Developers
Instant download Architecture Patterns with Python 1st Edition Harry Percival...
Full_Stack_Dule_1.NNNNNNNNNNNNNNNNNNNNNNNNNNNNNN[1].pptx
2 Day - WPF Training by Adil Mughal
Function Calling with the Vertex AI Gemini API
mlflow: Accelerating the End-to-End ML lifecycle
313534882-Modular-Programming-with-Python-Sample-Chapter.pptx
Ad

Recently uploaded (20)

PDF
Kalaari-SaaS-Founder-Playbook-2024-Edition-.pdf
PDF
Jana Ojana 2025 Prelims - School Quiz by Pragya - UEMK Quiz Club
PPTX
MALARIA - educational ppt for students..
PDF
Jana-Ojana Finals 2025 - School Quiz by Pragya - UEMK Quiz Club
PPSX
namma_kalvi_12th_botany_chapter_9_ppt.ppsx
PDF
English 2nd semesteNotesh biology biopsy results from the other day and I jus...
DOCX
HELMET DETECTION AND BIOMETRIC BASED VEHICLESECURITY USING MACHINE LEARNING.docx
PDF
gsas-cvs-and-cover-letters jhvgfcffttfghgvhg.pdf
PDF
Global strategy and action plan on oral health 2023 - 2030.pdf
PPTX
climate change of delhi impacts on climate and there effects
PDF
3-Elementary-Education-Prototype-Syllabi-Compendium.pdf
PPTX
GW4 BioMed Candidate Support Webinar 2025
PPTX
Juvenile delinquency-Crim Research day 3x
PDF
Design and Evaluation of a Inonotus obliquus-AgNP-Maltodextrin Delivery Syste...
PPTX
Environmental Sciences and Sustainability Chapter 2
PDF
BSc-Zoology-02Sem-DrVijay-Comparative anatomy of vertebrates.pdf
PPTX
Unit1_Kumod_deeplearning.pptx DEEP LEARNING
PDF
GSA-Past-Papers-2010-2024-2.pdf CSS examination
PDF
Developing speaking skill_learning_mater.pdf
PPTX
CHF refers to the condition wherein heart unable to pump a sufficient amount ...
Kalaari-SaaS-Founder-Playbook-2024-Edition-.pdf
Jana Ojana 2025 Prelims - School Quiz by Pragya - UEMK Quiz Club
MALARIA - educational ppt for students..
Jana-Ojana Finals 2025 - School Quiz by Pragya - UEMK Quiz Club
namma_kalvi_12th_botany_chapter_9_ppt.ppsx
English 2nd semesteNotesh biology biopsy results from the other day and I jus...
HELMET DETECTION AND BIOMETRIC BASED VEHICLESECURITY USING MACHINE LEARNING.docx
gsas-cvs-and-cover-letters jhvgfcffttfghgvhg.pdf
Global strategy and action plan on oral health 2023 - 2030.pdf
climate change of delhi impacts on climate and there effects
3-Elementary-Education-Prototype-Syllabi-Compendium.pdf
GW4 BioMed Candidate Support Webinar 2025
Juvenile delinquency-Crim Research day 3x
Design and Evaluation of a Inonotus obliquus-AgNP-Maltodextrin Delivery Syste...
Environmental Sciences and Sustainability Chapter 2
BSc-Zoology-02Sem-DrVijay-Comparative anatomy of vertebrates.pdf
Unit1_Kumod_deeplearning.pptx DEEP LEARNING
GSA-Past-Papers-2010-2024-2.pdf CSS examination
Developing speaking skill_learning_mater.pdf
CHF refers to the condition wherein heart unable to pump a sufficient amount ...
Ad

Objectoriented Python 1st Edition Irv Kalb

  • 1. Objectoriented Python 1st Edition Irv Kalb download https://ebookbell.com/product/objectoriented-python-1st-edition- irv-kalb-42304954 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Objectoriented Python 1st Edition Irv Kalb https://ebookbell.com/product/objectoriented-python-1st-edition-irv- kalb-36397474 Objectoriented Python 1 Converted Irv Kalb https://ebookbell.com/product/objectoriented-python-1-converted-irv- kalb-36430034 Objectoriented Python Master Oop Through Game Development And Gui Applications Kameron Hussain Frahaan Hussain https://ebookbell.com/product/objectoriented-python-master-oop- through-game-development-and-gui-applications-kameron-hussain-frahaan- hussain-79088142 Objectoriented Python Irv Kalb https://ebookbell.com/product/objectoriented-python-irv-kalb-42302770
  • 3. Objectoriented Python Irv Kalb https://ebookbell.com/product/objectoriented-python-irv-kalb-42322876 Objectoriented Python Irv Kalb https://ebookbell.com/product/objectoriented-python-irv-kalb-42302434 An Object Oriented Python Cookbook In Quantum Information Theory And Quantum Computing M S Ramkarthik https://ebookbell.com/product/an-object-oriented-python-cookbook-in- quantum-information-theory-and-quantum-computing-m-s- ramkarthik-46375732 Mastering Objectoriented Python Steven F Lott https://ebookbell.com/product/mastering-objectoriented-python-steven- f-lott-4706056 Mastering Objectoriented Python 2nd Edition 2nd Edition Steven F Lott https://ebookbell.com/product/mastering-objectoriented-python-2nd- edition-2nd-edition-steven-f-lott-10469262
  • 6. CONTENTS IN DETAIL TITLE PAGE COPYRIGHT DEDICATION ABOUT THE AUTHOR ACKNOWLEDGMENTS INTRODUCTION Who Is This Book For? Python Version(s) and Installation How Will I Explain OOP? What’s in the Book Development Environments Widgets and Example Games PART I: INTRODUCING OBJECT-ORIENTED PROGRAMMING CHAPTER 1: PROCEDURAL PYTHON EXAMPLES Higher or Lower Card Game Representing the Data Implementation Reusable Code Bank Account Simulations
  • 7. Analysis of Required Operations and Data Implementation 1—Single Account Without Functions Implementation 2—Single Account with Functions Implementation 3—Two Accounts Implementation 4—Multiple Accounts Using Lists Implementation 5—List of Account Dictionaries Common Problems with Procedural Implementation Object-Oriented Solution—First Look at a Class Summary CHAPTER 2: MODELING PHYSICAL OBJECTS WITH OBJECT- ORIENTED PROGRAMMING Building Software Models of Physical Objects State and Behavior: Light Switch Example Classes, Objects, and Instantiation Writing a Class in Python Scope and Instance Variables Differences Between Functions and Methods Creating an Object from a Class Calling Methods of an Object Creating Multiple Instances from the Same Class Python Data Types Are Implemented as Classes Definition of an Object Building a Slightly More Complicated Class Representing a More Complicated Physical Object as a Class Passing Arguments to a Method Multiple Instances Initialization Parameters Classes in Use
  • 8. OOP as a Solution Summary CHAPTER 3: MENTAL MODELS OF OBJECTS AND THE MEANING OF “SELF” Revisiting the DimmerSwitch Class High-Level Mental Model #1 A Deeper Mental Model #2 What Is the Meaning of “self”? Summary CHAPTER 4: MANAGING MULTIPLE OBJECTS Bank Account Class Importing Class Code Creating Some Test Code Creating Multiple Accounts Multiple Account Objects in a List Multiple Objects with Unique Identifiers Building an Interactive Menu Creating an Object Manager Object Building the Object Manager Object Main Code That Creates an Object Manager Object Better Error Handling with Exceptions try and except The raise Statement and Custom Exceptions Using Exceptions in Our Bank Program Account Class with Exceptions Optimized Bank Class Main Code That Handles Exceptions
  • 9. Calling the Same Method on a List of Objects Interface vs. Implementation Summary PART II: GRAPHICAL USER INTERFACES WITH PYGAME CHAPTER 5: INTRODUCTION TO PYGAME Installing Pygame Window Details The Window Coordinate System Pixel Colors Event-Driven Programs Using Pygame Bringing Up a Blank Window Drawing an Image Detecting a Mouse Click Handling the Keyboard Creating a Location-Based Animation Using Pygame rects Playing Sounds Playing Sound Effects Playing Background Music Drawing Shapes Reference for Primitive Shapes Summary CHAPTER 6: OBJECT-ORIENTED PYGAME Building the Screensaver Ball with OOP Pygame
  • 10. Creating a Ball Class Using the Ball Class Creating Many Ball Objects Creating Many, Many Ball Objects Building a Reusable Object-Oriented Button Building a Button Class Main Code Using a SimpleButton Creating a Program with Multiple Buttons Building a Reusable Object-Oriented Text Display Steps to Display Text Creating a SimpleText Class Demo Ball with SimpleText and SimpleButton Interface vs. Implementation Callbacks Creating a Callback Using a Callback with SimpleButton Summary CHAPTER 7: PYGAME GUI WIDGETS Passing Arguments into a Function or Method Positional and Keyword Parameters Additional Notes on Keyword Parameters Using None as a Default Value Choosing Keywords and Default Values Default Values in GUI Widgets The pygwidgets Package Setting Up Overall Design Approach
  • 11. Adding an Image Adding Buttons, Checkboxes, and Radio Buttons Text Output and Input Other pygwidgets Classes pygwidgets Example Program The Importance of a Consistent API Summary PART III: ENCAPSULATION, POLYMORPHISM, AND INHERITANCE CHAPTER 8: ENCAPSULATION Encapsulation with Functions Encapsulation with Objects Objects Own Their Data Interpretations of Encapsulation Direct Access and Why You Should Avoid It Strict Interpretation with Getters and Setters Safe Direct Access Making Instance Variables More Private Implicitly Private More Explicitly Private Decorators and @property Encapsulation in pygwidgets Classes A Story from the Real World Abstraction Summary CHAPTER 9: POLYMORPHISM
  • 12. Sending Messages to Real-World Objects A Classic Example of Polymorphism in Programming Example Using Pygame Shapes The Square Shape Class The Circle and Triangle Shape Classes The Main Program Creating Shapes Extending a Pattern pygwidgets Exhibits Polymorphism Polymorphism for Operators Magic Methods Comparison Operator Magic Methods A Rectangle Class with Magic Methods Main Program Using Magic Methods Math Operator Magic Methods Vector Example Creating a String Representation of Values in an Object A Fraction Class with Magic Methods Summary CHAPTER 10: INHERITANCE Inheritance in Object-Oriented Programming Implementing Inheritance Employee and Manager Example Base Class: Employee Subclass: Manager Test Code The Client’s View of a Subclass Real-World Examples of Inheritance InputNumber
  • 13. DisplayMoney Example Usage Multiple Classes Inheriting from the Same Base Class Abstract Classes and Methods How pygwidgets Uses Inheritance Class Hierarchy The Difficulty of Programming with Inheritance Summary CHAPTER 11: MANAGING MEMORY USED BY OBJECTS Object Lifetime Reference Count Garbage Collection Class Variables Class Variable Constants Class Variables for Counting Putting It All Together: Balloon Sample Program Module of Constants Main Program Code Balloon Manager Balloon Class and Objects Managing Memory: Slots Summary PART IV: USING OOP IN GAME DEVELOPMENT CHAPTER 12: CARD GAMES The Card Class The Deck Class
  • 14. The Higher or Lower Game Main Program Game Object Testing with __name__ Other Card Games Blackjack Deck Games with Unusual Card Decks Summary CHAPTER 13: TIMERS Timer Demonstration Program Three Approaches for Implementing Timers Counting Frames Timer Event Building a Timer by Calculating Elapsed Time Installing pyghelpers The Timer Class Displaying Time CountUpTimer CountDownTimer Summary CHAPTER 14: ANIMATION Building Animation Classes SimpleAnimation Class SimpleSpriteSheetAnimation Class Merging Two Classes Animation Classes in pygwidgets Animation Class
  • 15. SpriteSheetAnimation Class Common Base Class: PygAnimation Example Animation Program Summary CHAPTER 15: SCENES The State Machine Approach A pygame Example with a State Machine A Scene Manager for Managing Many Scenes A Demo Program Using a Scene Manager The Main Program Building the Scenes A Typical Scene Rock, Paper, Scissors Using Scenes Communication Between Scenes Requesting Information from a Target Scene Sending Information to a Target Scene Sending Information to All Scenes Testing Communications Among Scenes Implementation of the Scene Manager run() Method Main Methods Communication Between Scenes Summary CHAPTER 16: FULL GAME: DODGER Modal Dialogs Yes/No and Alert Dialogs Answer Dialogs
  • 16. Building a Full Game: Dodger Game Overview Implementation Extensions to the Game Summary CHAPTER 17: DESIGN PATTERNS AND WRAP-UP Model View Controller File Display Example Statistical Display Example Advantages of the MVC Pattern Wrap-Up INDEX
  • 17. OBJECT-ORIENTED PYTHON Master OOP by Building Games and GUIs by Irv Kalb
  • 18. Object-Oriented Python. Copyright © 2022 by Irv Kalb. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. First printing 25 24 23 22 21 1 2 3 4 5 6 7 8 9 ISBN-13: 978-1-7185-0206-2 (print) ISBN-13: 978-1-7185-0207-9 (ebook) Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Rachel Monaghan Production Editor: Kate Kaminski Developmental Editor: Liz Chadwick Cover Illustrator: James L. Barry Interior Design: Octopod Studios Technical Reviewer: Monte Davidoff Copyeditor: Rachel Head Compositor: Maureen Forys, Happenstance Type-O-Rama Proofreader: Paula L. Fleming Indexer: Valerie Haynes Perry The following images are reproduced with permission: Figure 2-1, photo by David Benbennick, printed under the Creative Commons Attribution- Share Alike 3.0 Unported license, https://creativecommons.org/licenses/by-sa/3.0/deed.en. For information on book distributors or translations, please contact No Starch Press, Inc. directly: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900; [email protected] www.nostarch.com Library of Congress Cataloging-in-Publication Data Names: Kalb, Irv, author. Title: Object-oriented Python: master OOP by building games and GUIs / Irv Kalb. Description: San Francisco : No Starch Press, [2021] | Includes index. | Identifiers: LCCN 2021044174 (print) | LCCN 2021044175 (ebook) | ISBN 9781718502062 (print) | ISBN 9781718502079 (ebook) Subjects: LCSH: Object-oriented programming (Computer science) | Python (Computer program language) Classification: LCC QA76.64 .K3563 2021 (print) | LCC QA76.64 (ebook) | DDC 005.1/17--dc23 LC record available at https://lccn.loc.gov/2021044174 LC ebook record available at https://lccn.loc.gov/2021044175 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a
  • 19. trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
  • 20. To my wonderful wife, Doreen. You are the glue that keeps our family together. Many years ago, I said, “I do,” but what I meant was, “I will.”
  • 21. About the Author Irv Kalb is an adjunct professor at UCSC Silicon Valley Extension and the University of Silicon Valley (formerly Cogswell Polytechnical College), where he teaches introductory and object-oriented programming courses in Python. Irv has a bachelor’s and a master’s degree in computer science, has been using object-oriented programming for over 30 years in a number of different computer languages, and has been teaching for over 10 years. He has decades of experience developing software, with a focus on educational software. As Furry Pants Productions, he and his wife created and shipped two edutainment CD-ROMs based on the character Darby the Dalmatian. Irv is also the author of Learn to Program with Python 3: A Step-by-Step Guide to Programming (Apress). Irv was heavily involved in the early development of the sport of Ultimate Frisbee®. He led the effort of writing many versions of the official rule book and co-authored and self-published the first book on the sport, Ultimate: Fundamentals of the Sport. About the Technical Reviewer Monte Davidoff is an independent software development consultant. His areas of expertise include DevOps and Linux. Monte has been programming in Python for over 20 years. He has used Python to develop a variety of software, including business-critical applications and embedded software.
  • 22. ACKNOWLEDGMENTS I would like to thank the following people, who helped make this book possible: Al Sweigart, for getting me started in the use of pygame (especially with his “Pygbutton” code) and for allowing me to use the concept of his “Dodger” game. Monte Davidoff, who was instrumental in helping me get the source code and documentation of that code to build correctly through the use of GitHub, Sphinx, and ReadTheDocs. He worked miracles using a myriad of tools to wrestle the appropriate files into submission. Monte Davidoff (yes, the same guy), for being an outstanding technical reviewer. Monte made excellent technical and writing suggestions throughout the book, and many of the code examples are more Pythonic and more OOP-ish because of his comments. Tep Sathya Khieu, who did a stellar job of drawing all the original diagrams for this book. I am not an artist (I don’t even play one on TV). Tep was able to take my primitive pencil sketches and turn them into clear, consistent pieces of art. Harrison Yung, Kevin Ly, and Emily Allis, for their contributions of artwork in some of the game art. The early reviewers, Illya Katsyuk, Jamie Kalb, Gergana Angelova, and Joe Langmuir, who found and corrected many typos and made excellent suggestions for modifications and clarifications. All the editors who worked on this book: Liz Chadwick (developmental editor), Rachel Head (copyeditor), and Kate Kaminski (production editor). They all made huge contributions by questioning and often rewording and reorganizing some of my
  • 23. explanations of concepts. They were also extremely helpful in adding and removing commas [do I need one here?] and lengthening my sentences as I am doing here to make sure that the point comes across cleanly (OK, I’ll stop!). I’m afraid that I’ll never understand when to use “which” versus “that,” or when to use a comma and when to use a dash, but I’m glad that they know! Thanks also to Maureen Forys (compositor) for her valuable contributions to the finished product. All the students who have been in my classes over the years at the UCSC Silicon Valley Extension and at the University of Silicon Valley (formerly Cogswell Polytechnical College). Their feedback, suggestions, smiles, frowns, light-bulb moments, frustrations, knowing head nods, and even thumbs-up (in Zoom classes during the COVID era) were extremely helpful in shaping the content of this book and my overall teaching style. Finally, my family, who supported me through the long process of writing, testing, editing, rewriting, editing, debugging, editing, rewriting, editing (and so on) this book and the associated code. I couldn’t have done it without them. I wasn’t sure if we had enough books in our library, so I wrote another one!
  • 24. INTRODUCTION This book is about a software development technique called object-oriented programming (OOP) and how it can be used with Python. Before OOP, programmers used an approach known as procedural programming, also called structured programming, which involves building a set of functions (procedures) and passing data around through calls to those functions. The OOP paradigm gives programmers an efficient way to combine code and data into cohesive units that are often highly reusable. In preparation for writing this book, I extensively researched existing literature and videos, looking specifically at the approaches taken to explain this important and wide-ranging topic. I found that instructors and writers typically start by defining certain key terms: class, instance variable, method, encapsulation, inheritance, polymorphism, and so on. While these are all important concepts, and I’ll cover all of them in depth in this book, I’ll begin in a different way: by considering the question, “What problem are we solving?” That is, if OOP is the solution, then what is the problem? To answer this question, I’ll start
  • 25. by presenting a few examples of programs built using procedural programming and identifying complications inherent in this style. Then I’ll show you how an object-oriented approach can make the construction of such programs much easier and the programs themselves more maintainable.
  • 26. Who Is This Book For? This book is intended for people who already have some familiarity with Python and with using basic functions from the Python Standard Library. I will assume that you understand the fundamental syntax of the language and can write small- to medium-sized programs using variables, assignment statements, if/elif/else statements, while and for loops, functions and function calls, lists, dictionaries, and so on. If you aren’t comfortable with all of these concepts, then I suggest that you get a copy of my earlier book, Learn to Program with Python 3 (Apress), and read that first. This is an intermediate-level text, so there are a number of more advanced topics that I will not address. For example, to keep the book practical, I will not often go into detail on the internal implementation of Python. For simplicity and clarity, and to keep the focus on mastering OOP techniques, the examples are written using a limited subset of the language. There are more advanced and concise ways to code in Python that are beyond the scope of this book. I will cover the underlying details of OOP in a mostly language- independent way, but will point out areas where there are differences between Python and other OOP languages. Having learned the basics of OOP-style coding through this book, if you wish, you should be able to easily apply these techniques to other OOP languages. Python Version(s) and Installation All the example code in this book was written and tested using Python versions 3.6 through 3.9. All the examples should work fine with version 3.6 or newer. Python is available for free at https://www.python.org. If you don’t have Python installed, or you want to upgrade to the latest version,
  • 27. go to that site, find the Downloads tab, and click the Download button. This will download an installable file onto your computer. Double-click the file that was downloaded to install Python. WINDOWS INSTALLATION If you’re installing on a Windows system, there is one important option that you need to set correctly. When running through the installation steps, you should see a screen like this: At the bottom of the dialog is a checkbox labeled “Add Python 3.x to PATH.” Please be sure to check this box (it defaults to unchecked). This setting will make the installation of the pygame package (which is introduced later in the book) work correctly.
  • 28. NOTE I am aware of the “PEP 8 – Style Guide for Python Code” and its specific recommendation to use the snake case convention (snake_case) for variable and function names. However, I’d been using the camel case naming convention (camelCase) for many years before the PEP 8 document was written and have become comfortable with it during my career. Therefore, all variable and function names in this book are written using camel case. How Will I Explain OOP? The examples in the first few chapters use text-based Python; these sample programs get input from the user and output information to the user purely in the form of text. I’ll introduce OOP by showing you how to develop text-based simulations of physical objects in code. We’ll start by creating representations of light switches, dimmer switches, and TV remote controls as objects. I’ll then show you how we can use OOP to simulate bank accounts and a bank that controls many accounts. Once we’ve covered the basics of OOP, I’ll introduce the pygame module, which allows programmers to write games and applications that use a graphical user interface (GUI). With GUI-based programs, the user intuitively interacts with buttons, checkboxes, text input and output fields, and other user-friendly widgets. I chose to use pygame with Python because this combination allows me to demonstrate OOP concepts in a highly visual way using elements on the screen. Pygame is extremely portable and runs on nearly every platform and operating system. All the sample programs that use the pygame package have been tested with the recently released pygame version 2.0. I’ve created a package called pygwidgets that works with pygame and implements a number of basic widgets, all of which are built
  • 29. using an OOP approach. I’ll introduce this package later in the book, providing sample code you can run and experiment with. This approach will allow you to see real, practical examples of key object- oriented concepts, while incorporating these techniques to produce fun, playable games. I’ll also introduce my pyghelpers package, which provides code to help write more complicated games and applications. All the example code shown in the book is available as a single download from the No Starch website: https://www.nostarch.com/object-oriented-python/. The code is also available on a chapter-by-chapter basis from my GitHub repository: https://github.com/IrvKalb/Object-Oriented- Python-Code/. What’s in the Book This book is divided into four parts. Part I introduces object-oriented programming: Chapter 1 provides a review of coding using procedural programming. I’ll show you how to implement a text-based card game and simulate a bank performing operations on one or more accounts. Along the way, I discuss common problems with the procedural approach. Chapter 2 introduces classes and objects and shows how you can represent real-world objects like light switches or a TV remote in Python using classes. You’ll see how an object-oriented approach solves the problems highlighted in the first chapter. Chapter 3 presents two mental models that you can use to think about what’s going on behind the scenes when you create objects in Python. We’ll use Python Tutor to step through code and see how objects are created. Chapter 4 demonstrates a standard way to handle multiple objects of the same type by introducing the concept of an object manager
  • 30. object. We’ll expand the bank account simulation using classes, and I’ll show you how to handle errors using exceptions. Part II focuses on building GUIs with pygame: Chapter 5 introduces the pygame package and the event-driven model of programming. We’ll build a few simple programs to get you started with placing graphics in a window and handling keyboard and mouse input, then develop a more complicated ball-bouncing program. Chapter 6 goes into much more detail on using OOP with pygame programs. We’ll rewrite the ball-bouncing program in an OOP style and develop some simple GUI elements. Chapter 7 introduces the pygwidgets module, which contains full implementations of many standard GUI elements (buttons, checkboxes, and so on), each developed as a class. Part III delves into the main tenets of OOP: Chapter 8 discusses encapsulation, which involves hiding implementation details from external code and placing all related methods in one place: a class. Chapter 9 introduces polymorphism—the idea that multiple classes can have methods with the same names—and shows how it enables you to make calls to methods in multiple objects, without having to know the type of each object. We’ll build a Shapes program to demonstrate this concept. Chapter 10 covers inheritance, which allows you to create a set of subclasses that all use common code built into a base class, rather than having to reinvent the wheel with similar classes. We’ll look at a few real-world examples where inheritance comes in handy, such as implementing an input field that only accepts numbers, then rewrite our Shapes example program to use this feature. Chapter 11 wraps up this part of the book by discussing some additional important OOP topics, mostly related to memory management. We’ll look at the lifetime of an object, and as an example we’ll build a small balloon-popping game.
  • 31. Part IV explores several topics related to using OOP in game development: Chapter 12 demonstrates how we can rebuild the card game developed in Chapter 1 as a pygame-based GUI program. I also show you how to build reusable Deck and Card classes that you can use in other card games you create. Chapter 13 covers timing. We’ll develop different timer classes that allow a program to keep running while concurrently checking for a given time limit. Chapter 14 explains animation classes you can use to show sequences of images. We’ll look at two animation techniques: building animations from a collection of separate image files and extracting and using multiple images from a single sprite sheet file. Chapter 15 explains the concept of a state machine, which represents and controls the flow of your programs, and a scene manager, which you can use to build a program with multiple scenes. To demonstrate the use of each of these, we’ll build two versions of a Rock, Paper, Scissors game. Chapter 16 discusses different types of modal dialogs, another important user interaction feature. We then walk through building a full-featured OOP-based video game called Dodger that demonstrates many of the techniques described in the book. Chapter 17 introduces the concept of design patterns, focusing on the Model View Controller pattern, then presents a dice-rolling program that uses this pattern to allow the user to visualize data in numerous different ways. It concludes with a short wrap-up for the book. Development Environments In this book, you’ll need to use the command line only minimally for installing software. All installation instructions will be clearly written out, so you won’t need to learn any additional command line syntax.
  • 32. Rather than using the command line for development, I believe strongly in using an interactive development environment (IDE). An IDE handles many of the details of the underlying operating system for you, and it allows you to write, edit, and run your code using a single program. IDEs are typically cross-platform, allowing programmers to easily move from a Mac to a Windows computer or vice versa. The short example programs in the book can be run in the IDLE development environment that is installed when you install Python. IDLE is very simple to use and works well for programs that can be written in a single file. When we get into more complicated programs that use multiple Python files, I encourage you to use a more sophisticated environment instead; I use the JetBrains PyCharm development environment, which handles multiple-file projects more easily. The Community Edition is available for free from https://www.jetbrains.com/, and I highly recommend it. PyCharm also has a fully integrated debugger that can be extremely useful when writing larger programs. For more information on how to use the debugger, please see my YouTube video “Debugging Python 3 with PyCharm” at https://www.youtube.com/watch? v=cxAOSQQwDJ4&t=43s/. Widgets and Example Games The book introduces and makes available two Python packages: pygwidgets and pyghelpers. Using these packages, you should be able to build full GUI programs—but more importantly, you should gain an understanding of how each of the widgets is coded as a class and used as an object. Incorporating various widgets, the example games in the book start out relatively simple and get progressively more complicated. Chapter 16 walks you through the development and implementation of a full-featured video game, complete with a high-scores table that is saved to a file.
  • 33. By the end of this book, you should be able to code your own games—card games, or video games in the style of Pong, Hangman, Breakout, Space Invaders, and so on. Object-oriented programming gives you the ability to write programs that can easily display and control multiple items of the same type, which is often required when building user interfaces and is frequently necessary in game play. Object-oriented programming is a general style that can be used in all aspects of programming, well beyond the game examples I use to demonstrate OOP techniques here. I hope you find this approach to learning OOP enjoyable. Let’s get started!
  • 34. PART I INTRODUCING OBJECT-ORIENTED PROGRAMMING This part of the book introduces you to object- oriented programming. We’ll discuss problems inherent in procedural code, then see how object-oriented programming addresses those concerns. Thinking in objects (with state and behavior) will give you a new perspective about how to write code. Chapter 1 provides a review of procedural Python. I start by presenting a text-based card game named Higher or Lower, then work through a few progressively more complex implementations of a bank account in Python to help you better understand common problems with coding in a procedural style. Chapter 2 shows how we might represent real-world objects in Python using classes. We’ll write a program to simulate a light switch, modify it to include dimming capabilities, then move on to a more complicated TV remote simulation. Chapter 3 gives you two different ways to think about what is going on behind the scenes when you create objects in Python. Chapter 4 then demonstrates a standard way to handle multiple objects of the same type (for example, consider a simple game like checkers where you have to keep track of many similar game
  • 35. pieces). We’ll expand the bank account programs from Chapter 1, and explore how to handle errors.
  • 36. 1 PROCEDURAL PYTHON EXAMPLES Introductory courses and books typically teach software development using the procedural programming style, which involves splitting a program into a number of functions (also known as procedures or subroutines). You pass data into functions, each of which performs one or more computations and, typically, passes back results. This book is about a different paradigm of programming known as object-oriented programming (OOP) that allows programmers to think differently about how to build software. Object-oriented programming gives programmers a way to combine code and data together into cohesive units, thereby avoiding some complications inherent in procedural programming.
  • 37. In this chapter, I’ll review a number of concepts in basic Python by building two small programs that incorporate various Python constructs. The first will be a small card game called Higher or Lower; the second will be a simulation of a bank, performing operations on one, two, and multiple accounts. Both will be built using procedural programming—that is, using the standard techniques of data and functions. Later, I’ll rewrite these programs using OOP techniques. The purpose of this chapter is to demonstrate some key problems inherent in procedural programming. With that understanding, the chapters that follow will explain how OOP solves those problems. Higher or Lower Card Game My first example is a simple card game called Higher or Lower. In this game, eight cards are randomly chosen from a deck. The first card is shown face up. The game asks the player to predict whether the next card in the selection will have a higher or lower value than the currently showing card. For example, say the card that’s shown is a 3. The player chooses “higher,” and the next card is shown. If that card has a higher value, the player is correct. In this example, if the player had chosen “lower,” they would have been incorrect. If the player guesses correctly, they get 20 points. If they choose incorrectly, they lose 15 points. If the next card to be turned over has the same value as the previous card, the player is incorrect. Representing the Data The program needs to represent a deck of 52 cards, which I’ll build as a list. Each of the 52 elements in the list will be a dictionary (a set of key/value pairs). To represent any card, each dictionary will contain three key/value pairs: 'rank', 'suit', and 'value'. The rank is the name of the card (Ace, 2, 3, … 10, Jack, Queen, King), but the value is an integer used for comparing cards (1, 2, 3, … 10, 11, 12, 13). For example, the Jack of Clubs would be represented as the following dictionary:
  • 38. {'rank': 'Jack', 'suit': 'Clubs', 'value': 11} Before the player plays a round, the list representing the deck is created and shuffled to randomize the order of the cards. I have no graphical representation of the cards, so each time the user chooses “higher” or “lower,” the program gets a card dictionary from the deck and prints the rank and the suit for the user. The program then compares the value of the new card to that of the previous card and gives feedback based on the correctness of the user’s answer. Implementation Listing 1-1 shows the code of the Higher or Lower game. NOTE As a reminder, the code associated with all the major listings in this book is available for download at https://www.nostarch.com/object-oriented-python/ and https://github.com/IrvKalb/Object-Oriented-Python-Code/. You can either download and run the code or type it in yourself. File: HigherOrLowerProcedural.py # HigherOrLower import random # Card constants SUIT_TUPLE = ('Spades', 'Hearts', 'Clubs', 'Diamonds') RANK_TUPLE = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King') NCARDS = 8 # Pass in a deck and this function returns a random card from the deck def getCard(deckListIn): thisCard = deckListIn.pop() # pop one off the top of the deck and return
  • 39. return thisCard # Pass in a deck and this function returns a shuffled copy of the deck def shuffle(deckListIn): deckListOut = deckListIn.copy() # make a copy of the starting deck random.shuffle(deckListOut) return deckListOut # Main code print('Welcome to Higher or Lower.') print('You have to choose whether the next card to be shown will be higher or lower than the current card.') print('Getting it right adds 20 points; get it wrong and you lose 15 points.') print('You have 50 points to start.') print() startingDeckList = [] 1 for suit in SUIT_TUPLE: for thisValue, rank in enumerate(RANK_TUPLE): cardDict = {'rank':rank, 'suit':suit, 'value':thisValue + 1} startingDeckList.append(cardDict) score = 50 while True: # play multiple games print() gameDeckList = shuffle(startingDeckList) 2 currentCardDict = getCard(gameDeckList) currentCardRank = currentCardDict['rank'] currentCardValue = currentCardDict['value'] currentCardSuit = currentCardDict['suit'] print('Starting card is:', currentCardRank + ' of ' + currentCardSuit) print() 3 for cardNumber in range(0, NCARDS): # play one game of this many cards answer = input('Will the next card be higher or lower than the ' + currentCardRank + ' of ' + currentCardSuit + '? (enter h or l): ') answer = answer.casefold() # force lowercase
  • 40. 4 nextCardDict = getCard(gameDeckList) nextCardRank = nextCardDict['rank'] nextCardSuit = nextCardDict['suit'] nextCardValue = nextCardDict['value'] print('Next card is:', nextCardRank + ' of ' + nextCardSuit) 5 if answer == 'h': if nextCardValue > currentCardValue: print('You got it right, it was higher') score = score + 20 else: print('Sorry, it was not higher') score = score - 15 elif answer == 'l': if nextCardValue < currentCardValue: score = score + 20 print('You got it right, it was lower') else: score = score - 15 print('Sorry, it was not lower') print('Your score is:', score) print() currentCardRank = nextCardRank currentCardValue = nextCardValue # don't need current suit 6 goAgain = input('To play again, press ENTER, or "q" to quit: ') if goAgain == 'q': break print('OK bye') Listing 1-1: A Higher or Lower game using procedural Python The program starts by creating a deck as a list 1. Each card is a dictionary made up of a rank, a suit, and a value. For each round of the game, I retrieve the first card from the deck and save the components in variables 2. For the next seven cards, the user is asked to predict whether the next card will be higher or lower than
  • 41. the most recently showing card 3. The next card is retrieved from the deck, and its components are saved in a second set of variables 4. The game compares the user’s answer to the card drawn and gives the user feedback and points based on the outcome 5. When the user has made predictions for all seven cards in the selection, we ask if they want to play again 6. This program demonstrates many elements of programming in general and Python in particular: variables, assignment statements, functions and function calls, if/else statements, print statements, while loops, lists, strings, and dictionaries. This book will assume you're already familiar with everything shown in this example. If there is anything in this program that is unfamiliar or not clear to you, it would probably be worth your time to review the appropriate material before moving on. Reusable Code Since this is a playing card–based game, the code obviously creates and manipulates a simulated deck of cards. If we wanted to write another card-based game, it would be great to be able to reuse the code for the deck and cards. In a procedural program, it can often be difficult to identify all the pieces of code associated with one portion of the program, such as the deck and cards in this example. In Listing 1-1, the code for the deck consists of two tuple constants, two functions, some main code to build a global list that represents the starting deck of 52 cards, and another global list that represents the deck that is used while the game is being played. Further, notice that even in a small program like this, the data and the code that manipulates the data might not be closely grouped together. Therefore, reusing the deck and card code in another program is not that easy or straightforward. In Chapter 12, we will revisit this program and show how an OOP solution makes reusing code like this much easier.
  • 42. Bank Account Simulations In this second example of procedural coding, I’ll present a number of variations of a program that simulates running a bank. In each new version of the program, I’ll add more functionality. Note that these programs are not production-ready; invalid user entries or misuse will lead to errors. The intent is to have you focus on how the code interacts with the data associated with one or more bank accounts. To start, consider what operations a client would want to do with a bank account and what data would be needed to represent an account. Analysis of Required Operations and Data A list of operations a person would want to do with a bank account would include: Create (an account) Deposit Withdraw Check balance Next, here is a minimal list of the data we would need to represent a bank account: Customer name Password Balance Notice that all the operations are action words (verbs) and all the data items are things (nouns). A real bank account would certainly be capable of many more operations and would contain additional pieces of data (such as the account holder’s address, phone number, and Social Security number), but to keep the discussion clear, I’ll start with just these four actions and three pieces of data. Further, to keep things simple and focused, I’ll make all amounts an integer number of dollars. I should also point out that in a real bank
  • 43. application, passwords would not be kept in cleartext (unencrypted) as it is in these examples. Implementation 1—Single Account Without Functions In the starting version in Listing 1-2, there is only a single account. File: Bank1_OneAccount.py # Non-OOP # Bank Version 1 # Single account 1 accountName = 'Joe' accountBalance = 100 accountPassword = 'soup' while True: 2 print() print('Press b to get the balance') print('Press d to make a deposit') print('Press w to make a withdrawal') print('Press s to show the account') print('Press q to quit') print() action = input('What do you want to do? ') action = action.lower() # force lowercase action = action[0] # just use first letter print() if action == 'b': print('Get Balance:') userPassword = input('Please enter the password: ') if userPassword != accountPassword: print('Incorrect password') else: print('Your balance is:', accountBalance) elif action == 'd': print('Deposit:') userDepositAmount = input('Please enter amount to deposit: ') userDepositAmount = int(userDepositAmount) userPassword = input('Please enter the password: ')
  • 44. if userDepositAmount < 0: print('You cannot deposit a negative amount!') elif userPassword != accountPassword: print('Incorrect password') else: # OK accountBalance = accountBalance + userDepositAmount print('Your new balance is:', accountBalance) elif action == 's': # show print('Show:') print(' Name', accountName) print(' Balance:', accountBalance) print(' Password:', accountPassword) print() elif action == 'q': break elif action == 'w': print('Withdraw:') userWithdrawAmount = input('Please enter the amount to withdraw: ') userWithdrawAmount = int(userWithdrawAmount) userPassword = input('Please enter the password: ') if userWithdrawAmount < 0: print('You cannot withdraw a negative amount') elif userPassword != accountPassword: print('Incorrect password for this account') elif userWithdrawAmount > accountBalance: print('You cannot withdraw more than you have in your account') else: #OK accountBalance = accountBalance - userWithdrawAmount print('Your new balance is:', accountBalance) print('Done')
  • 45. Listing 1-2: Bank simulation for a single account The program starts off by initializing three variables to represent the data of one account 1. Then it displays a menu that allows a choice of operations 2. The main code of the program acts directly on the global account variables. In this example, all the actions are at the main level; there are no functions in the code. The program works fine, but it may seem a little long. A typical approach to make longer programs clearer is to move related code into functions and make calls to those functions. We’ll explore that in the next implementation of the banking program. Implementation 2—Single Account with Functions In the version of the program in Listing 1-3, the code is broken up into separate functions, one for each action. Again, this simulation is for a single account. File: Bank2_OneAccountWithFunctions.py # Non-OOP # Bank 2 # Single account accountName = '' accountBalance = 0 accountPassword = '' 1 def newAccount(name, balance, password): global accountName, accountBalance, accountPassword accountName = name accountBalance = balance accountPassword = password def show(): global accountName, accountBalance, accountPassword print(' Name', accountName) print(' Balance:', accountBalance) print(' Password:', accountPassword) print()
  • 46. 2 def getBalance(password): global accountName, accountBalance, accountPassword if password != accountPassword: print('Incorrect password') return None return accountBalance 3 def deposit(amountToDeposit, password): global accountName, accountBalance, accountPassword if amountToDeposit < 0: print('You cannot deposit a negative amount!') return None if password != accountPassword: print('Incorrect password') return None accountBalance = accountBalance + amountToDeposit return accountBalance 4 def withdraw(amountToWithdraw, password): 5 global accountName, accountBalance, accountPassword if amountToWithdraw < 0: print('You cannot withdraw a negative amount') return None if password != accountPassword: print('Incorrect password for this account') return None if amountToWithdraw > accountBalance: print('You cannot withdraw more than you have in your account') return None 6 accountBalance = accountBalance - amountToWithdraw return accountBalance newAccount("Joe", 100, 'soup') # create an account while True: print() print('Press b to get the balance') print('Press d to make a deposit') print('Press w to make a withdrawal') print('Press s to show the account')
  • 47. print('Press q to quit') print() action = input('What do you want to do? ') action = action.lower() # force lowercase action = action[0] # just use first letter print() if action == 'b': print('Get Balance:') userPassword = input('Please enter the password: ') theBalance = getBalance(userPassword) if theBalance is not None: print('Your balance is:', theBalance) 7 elif action == 'd': print('Deposit:') userDepositAmount = input('Please enter amount to deposit: ') userDepositAmount = int(userDepositAmount) userPassword = input('Please enter the password: ') 8 newBalance = deposit(userDepositAmount, userPassword) if newBalance is not None: print('Your new balance is:', newBalance) --- snip calls to appropriate functions --- print('Done') Listing 1-3: Bank simulation for one account with functions In this version, I’ve built a function for each of the operations that we identified for a bank account (create 1, check balance 2, deposit 3, and withdraw 4) and rearranged the code so that the main code contains calls to the different functions. As a result, the main program is much more readable. For example, if the user types d to indicate that they want to make a deposit 7, the code now calls a function named deposit() 3, passing in the amount to be deposited and the account password the user entered.
  • 48. However, if you look at the definition of any of these functions—for example, the withdraw() function—you’ll see that the code uses global statements 5 to access (get or set) the variables that represent the account. In Python, a global statement is only required if you want to change the value of a global variable in a function. However, I am using them here to make it clear that these functions are referring to global variables, even if they are just getting a value. As a general programming tenet, functions should never modify global variables. A function should only use data that is passed into it, make calculations based on that data, and potentially return a result or results. The withdraw() function in this program does work, but it violates this rule by modifying the value of the global variable accountBalance 6 (in addition to accessing the value of the global variable accountPassword). Implementation 3—Two Accounts The version of the bank simulation program in Listing 1-4 uses the same approach as Listing 1-3 but adds the ability to have two accounts. File: Bank3_TwoAccounts.py # Non-OOP # Bank 3 # Two accounts account0Name = '' account0Balance = 0 account0Password = '' account1Name = '' account1Balance = 0 account1Password = '' nAccounts = 0 def newAccount(accountNumber, name, balance, password): 1 global account0Name, account0Balance, account0Password global account1Name, account1Balance, account1Password if accountNumber == 0:
  • 49. account0Name = name account0Balance = balance account0Password = password if accountNumber == 1: account1Name = name account1Balance = balance account1Password = password def show(): 2 global account0Name, account0Balance, account0Password global account1Name, account1Balance, account1Password if account0Name != '': print('Account 0') print(' Name', account0Name) print(' Balance:', account0Balance) print(' Password:', account0Password) print() if account1Name != '': print('Account 1') print(' Name', account1Name) print(' Balance:', account1Balance) print(' Password:', account1Password) print() def getBalance(accountNumber, password): 3 global account0Name, account0Balance, account0Password global account1Name, account1Balance, account1Password if accountNumber == 0: if password != account0Password: print('Incorrect password') return None return account0Balance if accountNumber == 1: if password != account1Password: print('Incorrect password') return None return account1Balance --- snipped additional deposit() and withdraw() functions --- --- snipped main code that calls functions above --- print('Done')
  • 50. Listing 1-4: Bank simulation for two accounts with functions Even with just two accounts, you can see that this approach gets out of hand quickly. First, we set three global variables for each account at 1, 2, and 3. Also, every function now has an if statement to choose which set of global variables to access or change. Any time we want to add another account, we’ll need to add another set of global variables and more if statements in every function. This is simply not a feasible approach. We need a different way to handle an arbitrary number of accounts. Implementation 4—Multiple Accounts Using Lists To more easily accommodate multiple accounts, in Listing 1-5 I’ll represent the data using lists. I’ll use three parallel lists in this version of the program: accountNamesList, accountPasswordsList, and accountBalancesList. File: Bank4_N_Accounts.py # Non-OOP Bank # Version 4 # Any number of accounts - with lists 1 accountNamesList = [] accountBalancesList = [] accountPasswordsList = [] def newAccount(name, balance, password): global accountNamesList, accountBalancesList, accountPasswordsList 2 accountNamesList.append(name) accountBalancesList.append(balance) accountPasswordsList.append(password) def show(accountNumber): global accountNamesList, accountBalancesList, accountPasswordsList print('Account', accountNumber) print(' Name', accountNamesList[accountNumber]) print(' Balance:', accountBalancesList[accountNumber])
  • 51. print(' Password:', accountPasswordsList[accountNumber]) print() def getBalance(accountNumber, password): global accountNamesList, accountBalancesList, accountPasswordsList if password != accountPasswordsList[accountNumber]: print('Incorrect password') return None return accountBalancesList[accountNumber] --- snipped additional functions --- # Create two sample accounts 3 print("Joe's account is account number:", len(accountNamesList)) newAccount("Joe", 100, 'soup') 4 print("Mary's account is account number:", len(accountNamesList)) newAccount("Mary", 12345, 'nuts') while True: print() print('Press b to get the balance') print('Press d to make a deposit') print('Press n to create a new account') print('Press w to make a withdrawal') print('Press s to show all accounts') print('Press q to quit') print() action = input('What do you want to do? ') action = action.lower() # force lowercase action = action[0] # just use first letter print() if action == 'b': print('Get Balance:') 5 userAccountNumber = input('Please enter your account number: ') userAccountNumber = int(userAccountNumber) userPassword = input('Please enter the password: ') theBalance = getBalance(userAccountNumber, userPassword) if theBalance is not None:
  • 52. print('Your balance is:', theBalance) --- snipped additional user interface --- print('Done') Listing 1-5: Bank simulation with a parallel lists At the beginning of the program, I set all three lists to the empty list 1. To create a new account, I append the appropriate value to each of the three lists 2. Since I am now dealing with multiple accounts, I use the basic concept of a bank account number. Every time a user creates an account, the code uses the len() function on one of the lists and returns that number as the user’s account number 3, 4. When I create an account for the first user, the length of the accountNamesList is zero. Therefore, the first account created will be given account number 0, the second account is given account number 1, and so on. Then, like at a real bank, to do any operation after creating an account (like deposit or withdraw funds), the user must supply their account number 5. However, this code is still working with global data; now there are three global lists of data. Imagine viewing this data as a spreadsheet. It might look like Table 1-1. Table 1-1: A Table of Our Data Account number Name Password Balance 0 Joe soup 100 1 Mary nuts 3550 2 Bill frisbee 1000 3 Sue xxyyzz 750 4 Henry PW 10000 The data is maintained as three global Python lists, where each list represents a column in this table. For example, as you can see
  • 53. from the highlighted column, all the passwords are grouped together as one list. The users’ names are grouped in another list, and the balances are grouped in a third list. With this approach, to get information about one account, you need to access these lists with a common index value. While this works, it seems extremely awkward. The data is not grouped in a logical way. For example, it doesn’t seem right to keep all users’ passwords together. Further, every time you add a new attribute to an account, like an address or phone number, you need to create and access another global list. Instead, what you really want is a grouping that represents a row in the same spreadsheet, as in Table 1-2. Table 1-2: A Table of Our Data Account number Name Password Balance 0 Joe soup 100 1 Mary nuts 3550 2 Bill frisbee 1000 3 Sue xxyyzz 750 4 Henry PW 10000 With this approach, each row represents the data associated with a single bank account. While this is the same data, this grouping is a much more natural way of representing an account. Implementation 5—List of Account Dictionaries To implement this last approach, I’ll use a slightly more complicated data structure. In this version, I’ll create a list of accounts, where each account (each element of this list) is a dictionary that looks like this: {'name':<someName>, 'password':<somePassword>, 'balance': <someBalance>}
  • 54. NOTE In this book, whenever I present a value in angle brackets (<>), this means you should replace that item (including the brackets) with a value of your choosing. For example, in the preceding code line, <someName>, <somePassword>, and <someBalance> are placeholders and should be replaced with actual values. The code for the final implementation is presented in Listing 1-6. File: Bank5_Dictionary.py # Non-OOP Bank # Version 5 # Any number of accounts - with a list of dictionaries accountsList = [] 1 def newAccount(aName, aBalance, aPassword): global accountsList newAccountDict = {'name':aName, 'balance':aBalance, 'password':aPassword} accountsList.append(newAccountDict) 2 def show(accountNumber): global accountsList print('Account', accountNumber) thisAccountDict = accountsList[accountNumber] print(' Name', thisAccountDict['name']) print(' Balance:', thisAccountDict['balance']) print(' Password:', thisAccountDict['password']) print() def getBalance(accountNumber, password): global accountsList thisAccountDict = accountsList[accountNumber] 3 if password != thisAccountDict['password']: print('Incorrect password') return None return thisAccountDict['balance']
  • 55. Another Random Document on Scribd Without Any Related Topics
  • 56. Ah, God! What had she done! How had she dared to throw away her happiness like this. This was the only man who had ever understood her. Was it too late? Could it be too late? She was that glove that he held in his fingers. . . . “And then the fact that you had no friends and never had made friends with people. How I understood that, for neither had I. Is it just the same now?” “Yes,” she breathed. “Just the same. I am as alone as ever.” “So am I,” he laughed gently, “just the same.” Suddenly with a quick gesture he handed her back the glove and scraped his chair on the floor, “But what seemed to me so mysterious then is perfectly plain to me now. And to you, too, of course. . . . It simply was that we were such egoists, so self- engrossed, so wrapped up in ourselves that we hadn’t a corner in our hearts for anybody else. Do you know,” he cried, naive and hearty, and dreadfully like another side of that old self again, “I began studying a Mind System when I was in Russia, and I found that we were not peculiar at all. It’s quite a well known form of . . .” She had gone. He sat there, thunder-struck, astounded beyond words. . . . And then he asked the waitress for his bill. “But the cream has not been touched,” he said. “Please do not charge me for it.”
  • 57. The Little Governess Oh, dear, how she wished that it wasn’t night-time. She’d have much rather travelled by day, much much rather. But the lady at the Governess Bureau had said: “You had better take an evening boat and then if you get into a compartment for ‘Ladies Only’ in the train you will be far safer than sleeping in a foreign hotel. Don’t go out of the carriage; don’t walk about the corridors and be sure to lock the lavatory door if you go there. The train arrives at Munich at eight o’clock, and Frau Arnholdt says that the Hotel Grunewald is only one minute away. A porter can take you there. She will arrive at six the same evening, so you will have a nice quiet day to rest after the journey and rub up your German. And when you want anything to eat I would advise you to pop into the nearest baker’s and get a bun and some coffee. You haven’t been abroad before, have you?” “No.” “Well, I always tell my girls that it’s better to mistrust people at first rather than trust them, and it’s safer to suspect people of evil intentions rather than good ones. . . . It sounds rather hard but we’ve got to be women of the world, haven’t we?” It had been nice in the Ladies’ Cabin. The stewardess was so kind and changed her money for her and tucked up her feet. She lay on one of the hard pink-sprigged couches and watched the other passengers, friendly and natural, pinning their hats to the bolsters, taking off their boots and skirts, opening dressing-cases and arranging mysterious rustling little packages, tying their heads up in veils before lying down. Thud, thud, thud, went the steady screw of the steamer. The stewardess pulled a green shade over the light and sat down by the stove, her skirt turned back over her knees, a long piece of knitting on her lap. On a shelf above her head there was a
  • 58. water-bottle with a tight bunch of flowers stuck in it. “I like travelling very much,” thought the little governess. She smiled and yielded to the warm rocking. But when the boat stopped and she went up on deck, her dress- basket in one hand, her rug and umbrella in the other, a cold, strange wind flew under her hat. She looked up at the masts and spars of the ship black against a green glittering sky and down to the dark landing stage where strange muffled figures lounged, waiting; she moved forward with the sleepy flock, all knowing where to go to and what to do except her, and she felt afraid. Just a little— just enough to wish—oh, to wish that it was daytime and that one of those women who had smiled at her in the glass, when they both did their hair in the Ladies’ Cabin, was somewhere near now. “Tickets, please. Show your tickets. Have your tickets ready.” She went down the gangway balancing herself carefully on her heels. Then a man in a black leather cap came forward and touched her on the arm. “Where for, Miss?” He spoke English—he must be a guard or a stationmaster with a cap like that. She had scarcely answered when he pounced on her dress-basket. “This way,” he shouted, in a rude, determined voice, and elbowing his way he strode past the people. “But I don’t want a porter.” What a horrible man! “I don’t want a porter. I want to carry it myself.” She had to run to keep up with him, and her anger, far stronger than she, ran before her and snatched the bag out of the wretch’s hand. He paid no attention at all, but swung on down the long dark platform, and across a railway line. “He is a robber.” She was sure he was a robber as she stepped between the silvery rails and felt the cinders crunch under her shoes. On the other side—oh, thank goodness!—there was a train with Munich written on it. The man stopped by the huge lighted carriages. “Second class?” asked the insolent voice. “Yes, a Ladies’ compartment.” She was quite out of breath. She opened her little purse to find something small enough to give this horrible man while he tossed her dress-basket into the rack of an empty carriage that had a ticket, Dames Seules, gummed on window. She got into the train and handed twenty centimes. “What’s this?” shouted the man,
  • 59. glaring at the money and then at her, holding it up to his nose, sniffing at it as though he had never in his life seen, much less held, such a sum. “It’s a franc. You know that, don’t you? It’s a franc. That’s my fare!” A franc! Did he imagine that she was going to give him a franc for playing a trick like that just because she was a girl and travelling alone at night? Never, never! She squeezed her purse in her hand and simply did not see him—she looked at a view of St. Malo on the wall opposite and simply did not hear him. “Ah, no. Ah, no. Four sous. You make a mistake. Here, take it. It’s a franc I want.” He leapt on to the step of the train and threw the money on to her lap. Trembling with terror she screwed herself tight, tight, and put out an icy hand and took the money—stowed it away in her hand. “That’s all you’re going to get,” she said. For a minute or two she felt his sharp eyes pricking her all over, while he nodded slowly, pulling down his mouth: “Ve-ry well. Trrrès bien.” He shrugged his shoulders and disappeared into the dark. Oh, the relief! How simply terrible that had been! As she stood up to feel if the dress-basket was firm she caught sight of herself in the mirror, quite white, with big round eyes. She untied her “motor veil” and unbuttoned her green cape. “But it’s all over now,” she said to the mirror face, feeling in some way that it was more frightened than she. People began to assemble on the platform. They stood together in little groups talking; a strange light from the station lamps painted their faces almost green. A little boy in red clattered up with a huge tea wagon and leaned against it, whistling and flicking his boots with a serviette. A woman in a black alpaca apron pushed a barrow with pillows for hire. Dreamy and vacant she looked—like a woman wheeling a perambulator—up and down, up and down—with a sleeping baby inside it. Wreaths of white smoke floated up from somewhere and hung below the roof like misty vines. “How strange it all is,” thought the little governess, “and the middle of the night, too.” She looked out from her safe corner, frightened no longer but proud that she had not given that franc. “I can look after myself—of course I can. The great thing is not to——” Suddenly from the corridor there came a stamping of feet and men’s voices, high and
  • 60. broken with snatches of loud laughter. They were coming her way. The little governess shrank into her corner as four young men in bowler hats passed, staring through the door and window. One of them, bursting with the joke, pointed to the notice Dames Seules and the four bent down the better to see the one little girl in the corner. Oh dear, they were in the carriage next door. She heard them tramping about and then a sudden hush followed by a tall thin fellow with a tiny black moustache who flung her door open. “If mademoiselle cares to come in with us,” he said, in French. She saw the others crowding behind him, peeping under his arm and over his shoulder, and she sat very straight and still. “If mademoiselle will do us the honour,” mocked the tall man. One of them could be quiet no longer; his laughter went off in a loud crack. “Mademoiselle is serious,” persisted the young man, bowing and grimacing. He took off his hat with a flourish, and she was alone again. “En voiture. En voi-ture!” Some one ran up and down beside the train. “I wish it wasn’t night-time. I wish there was another woman in the carriage. I’m frightened of the men next door.” The little governess looked out to see her porter coming back again—the same man making for her carriage with his arms full of luggage. But —but what was he doing? He put his thumb nail under the label Dames Seules and tore it right off and then stood aside squinting at her while an old man wrapped in a plaid cape climbed up the high step. “But this is a ladies’ compartment.” “Oh, no, Mademoiselle, you make a mistake. No, no, I assure you. Merci, Monsieur.” “En voi- turre!” A shrill whistle. The porter stepped off triumphant and the train started. For a moment or two big tears brimmed her eyes and through them she saw the old man unwinding a scarf from his neck and untying the flaps of his Jaeger cap. He looked very old. Ninety at least. He had a white moustache and big gold-rimmed spectacles with little blue eyes behind them and pink wrinkled cheeks. A nice face—and charming the way he bent forward and said in halting French: “Do I disturb you, Mademoiselle? Would you rather I took all these things out of the rack and found another carriage?” What! that old man have to move all those heavy things just because she . . .
  • 61. “No, it’s quite all right. You don’t disturb me at all.” “Ah, a thousand thanks.” He sat down opposite her and unbuttoned the cape of his enormous coat and flung it off his shoulders. The train seemed glad to have left the station. With a long leap it sprang into the dark. She rubbed a place in the window with her glove but she could see nothing—just a tree outspread like a black fan or a scatter of lights, or the line of a hill, solemn and huge. In the carriage next door the young men started singing “Un, deux, trois.” They sang the same song over and over at the tops of their voices. “I never could have dared to go to sleep if I had been alone,” she decided. “I couldn’t have put my feet up or even taken off my hat.” The singing gave her a queer little tremble in her stomach and, hugging herself to stop it, with her arms crossed under her cape, she felt really glad to have the old man in the carriage with her. Careful to see that he was not looking she peeped at him through her long lashes. He sat extremely upright, the chest thrown out, the chin well in, knees pressed together, reading a German paper. That was why he spoke French so funnily. He was a German. Something in the army, she supposed—a Colonel or a General—once, of course, not now; he was too old for that now. How spick and span he looked for an old man. He wore a pearl pin stuck in his black tie and a ring with a dark red stone on his little finger; the tip of a white silk handkerchief showed in the pocket of his double-breasted jacket. Somehow, altogether, he was really nice to look at. Most old men were so horrid. She couldn’t bear them doddery—or they had a disgusting cough or something. But not having a beard—that made all the difference—and then his cheeks were so pink and his moustache so very white. Down went the German paper and the old man leaned forward with the same delightful courtesy: “Do you speak German, Mademoiselle?” “Ja, ein wenig, mehr als Franzosisch,” said the little governess, blushing a deep pink colour that spread slowly over her cheeks and made her blue eyes look almost black. “Ach, so!” The old man bowed graciously. “Then perhaps you would care to look at some illustrated papers.” He
  • 62. slipped a rubber band from a little roll of them and handed them across. “Thank you very much.” She was very fond of looking at pictures, but first she would take off her hat and gloves. So she stood up, unpinned the brown straw and put it neatly in the rack beside the dress-basket, stripped off her brown kid gloves, paired them in a tight roll and put them in the crown of the hat for safety, and then sat down again, more comfortably this time, her feet crossed, the papers on her lap. How kindly the old man in the corner watched her bare little hand turning over the big white pages, watched her lips moving as she pronounced the long words to herself, rested upon her hair that fairly blazed under the light. Alas! how tragic for a little governess to possess hair that made one think of tangerines and marigolds, of apricots and tortoiseshell cats and champagne! Perhaps that was what the old man was thinking as he gazed and gazed, and that not even the dark ugly clothes could disguise her soft beauty. Perhaps the flush that licked his cheeks and lips was a flush of rage that anyone so young and tender should have to travel alone and unprotected through the night. Who knows he was not murmuring in his sentimental German fashion: “Ja, es ist eine Tragœdie! Would to God I were the child’s grandpapa!” “Thank you very much. They were very interesting.” She smiled prettily handing back the papers. “But you speak German extremely well,” said the old man. “You have been in Germany before, of course?” “Oh no, this is the first time”—a little pause, then—“this is the first time that I have ever been abroad at all.” “Really! I am surprised. You gave me the impression, if I may say so, that you were accustomed to travelling.” “Oh, well—I have been about a good deal in England, and to Scotland, once.” “So. I myself have been in England once, but I could not learn English.” He raised one hand and shook his head, laughing. “No, it was too difficult for me. . . . ‘Ow- do-you-do. Please vich is ze vay to Leicestaire Squaare.’” She laughed too. “Foreigners always say . . .” They had quite a little talk about it. “But you will like Munich,” said the old man. “Munich is a wonderful city. Museums, pictures, galleries, fine buildings and shops, concerts, theatres, restaurants—all are in Munich. I have
  • 63. travelled all over Europe many, many times in my life, but it is always to Munich that I return. You will enjoy yourself there.” “I am not going to stay in Munich,” said the little governess, and she added shyly, “I am going to a post as governess to a doctor’s family in Augsburg.” “Ah, that was it.” Augsburg he knew. Augsburg—well— was not beautiful. A solid manufacturing town. But if Germany was new to her he hoped she would find something interesting there too. “I am sure I shall.” “But what a pity not to see Munich before you go. You ought to take a little holiday on your way”—he smiled—“and store up some pleasant memories.” “I am afraid I could not do that,” said the little governess, shaking her head, suddenly important and serious. “And also, if one is alone . . .” He quite understood. He bowed, serious too. They were silent after that. The train shattered on, baring its dark, flaming breast to the hills and to the valleys. It was warm in the carriage. She seemed to lean against the dark rushing and to be carried away and away. Little sounds made themselves heard; steps in the corridor, doors opening and shutting —a murmur of voices—whistling. . . . Then the window was pricked with long needles of rain. . . . But it did not matter . . . it was outside . . . and she had her umbrella . . . she pouted, sighed, opened and shut her hands once and fell fast asleep. “Pardon! Pardon!” The sliding back of the carriage door woke her with a start. What had happened? Some one had come in and gone out again. The old man sat in his corner, more upright than ever, his hands in the pockets of his coat, frowning heavily. “Ha! ha! ha!” came from the carriage next door. Still half asleep, she put her hands to her hair to make sure it wasn’t a dream. “Disgraceful!” muttered the old man more to himself than to her. “Common, vulgar fellows! I am afraid they disturbed you, gracious Fräulein, blundering in here like that.” No, not really. She was just going to wake up, and she took out silver watch to look at the time. Half-past four. A cold blue light filled the window panes. Now when she rubbed a place she could see bright patches of fields, a clump of white houses like mushrooms, a road “like a picture” with poplar trees on either side, a
  • 64. thread of river. How pretty it was! How pretty and how different! Even those pink clouds in the sky looked foreign. It was cold, but she pretended that it was far colder and rubbed her hands together and shivered, pulling at the collar of her coat because she was so happy. The train began to slow down. The engine gave a long shrill whistle. They were coming to a town. Taller houses, pink and yellow, glided by, fast asleep behind their green eyelids, and guarded by the poplar trees that quivered in the blue air as if on tiptoe, listening. In one house a woman opened the shutters, flung a red and white mattress across the window frame and stood staring at the train. A pale woman with black hair and a white woollen shawl over her shoulders. More women appeared at the doors and at the windows of the sleeping houses. There came a flock of sheep. The shepherd wore a blue blouse and pointed wooden shoes. Look! look what flowers—and by the railway station too! Standard roses like bridesmaids’ bouquets, white geraniums, waxy pink ones that you would never see out of a greenhouse at home. Slower and slower. A man with a watering-can was spraying the platform. “A-a-a-ah!” Somebody came running and waving his arms. A huge fat woman waddled through the glass doors of the station with a tray of strawberries. Oh, she was thirsty! She was very thirsty! “A-a-a-ah!” The same somebody ran back again. The train stopped. The old man pulled his coat round him and got up, smiling at her. He murmured something she didn’t quite catch, but she smiled back at him as he left the carriage. While he was away the little governess looked at herself again in the glass, shook and patted herself with the precise practical care of a girl who is old enough to travel by herself and has nobody else to assure her that she is “quite all right behind.” Thirsty and thirsty! The air tasted of water. She let down the window and the fat woman with the strawberries passed as if on purpose; holding up the tray to her. “Nein, danke,” said the little governess, looking at the big berries on their gleaming leaves. “Wie viel?” she asked as the fat woman moved away. “Two marks fifty, Fräulein.” “Good gracious!” She came in from the window and sat
  • 65. down in the corner, very sobered for a minute. Half a crown! “H-o-o- o-o-o-e-e-e!” shrieked the train, gathering itself together to be off again. She hoped the old man wouldn’t be left behind. Oh, it was daylight—everything was lovely if only she hadn’t been so thirsty. Where was the old man—oh, here he was—she dimpled at him as though he were an old accepted friend as he closed the door and, turning, took from under his cape a basket of the strawberries. “If Fräulein would honour me by accepting these . . .” “What for me?” But she drew back and raised her hands as though he were about to put a wild little kitten on her lap. “Certainly, for you,” said the old man. “For myself it is twenty years since I was brave enough to eat strawberries.” “Oh, thank you very much. Danke bestens,” she stammered, “sie sind so sehr schön!” “Eat them and see,” said the old man looking pleased and friendly. “You won’t have even one?” “No, no, no.” Timidly and charmingly her hand hovered. They were so big and juicy she had to take two bites to them—the juice ran all down her fingers—and it was while she munched the berries that she first thought of the old man as a grandfather. What a perfect grandfather he would make! Just like one out of a book! The sun came out, the pink clouds in the sky, the strawberry clouds were eaten by the blue. “Are they good?” asked the old man. “As good as they look?” When she had eaten them she felt she had known him for years. She told him about Frau Arnholdt and how she had got the place. Did he know the Hotel Grunewald? Frau Arnholdt would not arrive until the evening. He listened, listened until he knew as much about the affair as she did, until he said—not looking at her—but smoothing the palms of his brown suède gloves together: “I wonder if you would let me show you a little of Munich to-day. Nothing much —but just perhaps a picture gallery and the Englischer Garten. It seems such a pity that you should have to spend the day at the hotel, and also a little uncomfortable . . . in a strange place. Nicht wahr? You would be back there by the early afternoon or whenever
  • 66. you wish, of course, and you would give an old man a great deal of pleasure.” It was not until long after she had said “Yes”—because the moment she had said it and he had thanked her he began telling her about his travels in Turkey and attar of roses—that she wondered whether she had done wrong. After all, she really did not know him. But he was so old and he had been so very kind—not to mention the strawberries. . . . And she couldn’t have explained the reason why she said “No,” and it was her last day in a way, her last day to really enjoy herself in. “Was I wrong? Was I?” A drop of sunlight fell into her hands and lay there, warm and quivering. “If I might accompany you as far as the hotel,” he suggested, “and call for you again at about ten o’clock.” He took out his pocket-book and handed her a card. “Herr Regierungsrat. . . .” He had a title! Well, it was bound to be all right! So after that the little governess gave herself up to the excitement of being really abroad, to looking out and reading the foreign advertisement signs, to being told about the places they came to—having her attention and enjoyment looked after by the charming old grandfather—until they reached Munich and the Hauptbahnhof. “Porter! Porter!” He found her a porter, disposed of his own luggage in a few words, guided her through the bewildering crowd out of the station down the clean white steps into the white road to the hotel. He explained who she was to the manager as though all this had been bound to happen, and then for one moment her little hand lost itself in the big brown suède ones. “I will call for you at ten o’clock.” He was gone. “This way, Fräulein,” said a waiter, who had been dodging behind the manager’s back, all eyes and ears for the strange couple. She followed him up two flights of stairs into a dark bedroom. He dashed down her dress-basket and pulled up a clattering, dusty blind. Ugh! what an ugly, cold room—what enormous furniture! Fancy spending the day in here! “Is this the room Frau Arnholdt ordered?” asked the little governess. The waiter had a curious way of staring as if there was something funny about her. He pursed up his lips about to whistle, and then changed his mind. “Gewiss,” he said. Well, why
  • 67. didn’t he go? Why did he stare so? “Gehen Sie,” said the little governess, with frigid English simplicity. His little eyes, like currants, nearly popped out of his doughy cheeks. “Gehen Sie sofort,” she repeated icily. At the door he turned. “And the gentleman,” said he, “shall I show the gentleman upstairs when he comes?” Over the white streets big white clouds fringed with silver—and sunshine everywhere. Fat, fat coachmen driving fat cabs; funny women with little round hats cleaning the tramway lines; people laughing and pushing against one another; trees on both sides of the streets and everywhere you looked almost, immense fountains; a noise of laughing from the footpaths or the middle of the streets or the open windows. And beside her, more beautifully brushed than ever, with a rolled umbrella in one hand and yellow gloves instead of brown ones, her grandfather who had asked her to spend the day. She wanted to run, she wanted to hang on his arm, she wanted to cry every minute, “Oh, I am so frightfully happy!” He guided her across the roads, stood still while she “looked,” and his kind eyes beamed on her and he said “just whatever you wish.” She ate two white sausages and two little rolls of fresh bread at eleven o’clock in the morning and she drank some beer, which he told her wasn’t intoxicating, wasn’t at all like English beer, out of a glass like a flower vase. And then they took a cab and really she must have seen thousands and thousands of wonderful classical pictures in about a quarter of an hour! “I shall have to think them over when I am alone.” . . . But when they came out of the picture gallery it was raining. The grandfather unfurled his umbrella and held it over the little governess. They started to walk to the restaurant for lunch. She, very close beside him so that he should have some of the umbrella, too. “It goes easier,” he remarked in a detached way, “if you take my arm, Fräulein. And besides it is the custom in Germany.” So she took his arm and walked beside him while he pointed out the famous statues, so interested that he quite forgot to put down the umbrella even when the rain was long over.
  • 68. After lunch they went to a café to hear a gipsy band, but she did not like that at all. Ugh! such horrible men where there with heads like eggs and cuts on their faces, so she turned her chair and cupped her burning cheeks in her hands and watched her old friend instead. . . . Then they went to the Englischer Garten. “I wonder what the time is,” asked the little governess. “My watch has stopped. I forgot to wind it in the train last night. We’ve seen such a lot of things that I feel it must be quite late.” “Late!” He stopped in front of her laughing and shaking his head in a way she had begun to know. “Then you have not really enjoyed yourself. Late! Why, we have not had any ice cream yet!” “Oh, but I have enjoyed myself,” she cried, distressed, “more than I can possibly say. It has been wonderful! Only Frau Arnholdt is to be at the hotel at six and I ought to be there by five.” “So you shall. After the ice cream I shall put you into a cab and you can go there comfortably.” She was happy again. The chocolate ice cream melted—melted in little sips a long way down. The shadows of the trees danced on the table cloths, and she sat with her back safely turned to the ornamental clock that pointed to twenty-five minutes to seven. “Really and truly,” said the little governess earnestly, “this has been the happiest day of my life. I’ve never even imagined such a day.” In spite of the ice cream her grateful baby heart glowed with love for the fairy grandfather. So they walked out of the garden down a long alley. The day was nearly over. “You see those big buildings opposite,” said the old man. “The third storey—that is where I live. I and the old housekeeper who looks after me.” She was very interested. “Now just before I find a cab for you, will you come and see my little ‘home’ and let me give you a bottle of the attar of roses I told you about in the train? For remembrance?” She would love to. “I’ve never seen a bachelor’s flat in my life,” laughed the little governess. The passage was quite dark. “Ah, I suppose my old woman has gone out to buy me a chicken. One moment.” He opened a door and stood aside for her to pass, a little shy but curious, into a strange room. She did not know quite what to say. It wasn’t pretty. In a way
  • 69. it was very ugly—but neat, and, she supposed, comfortable for such an old man. “Well, what do you think of it?” He knelt down and took from a cupboard a round tray with two pink glasses and a tall pink bottle. “Two little bedrooms beyond,” he said gaily, “and a kitchen. It’s enough, eh?” “Oh, quite enough.” “And if ever you should be in Munich and care to spend a day or two—why there is always a little nest—a wing of a chicken, and a salad, and an old man delighted to be your host once more and many many times, dear little Fräulein!” He took the stopper out of the bottle and poured some wine into the two pink glasses. His hand shook and the wine spilled over the tray. It was very quiet in the room. She said: “I think I ought to go now.” “But you will have a tiny glass of wine with me—just one before you go?” said the old man. “No, really no. I never drink wine. I—I have promised never to touch wine or anything like that.” And though he pleaded and though she felt dreadfully rude, especially when he seemed to take it to heart so, she was quite determined. “No, really, please.” “Well, will you just sit down on the sofa for five minutes and let me drink your health?” The little governess sat down on the edge of the red velvet couch and he sat down beside her and drank her health at a gulp. “Have you really been happy to-day?” asked the old man, turning round, so close beside her that she felt his knee twitching against hers. Before she could answer he held her hands. “And are you going to give me one little kiss before you go?” he asked, drawing her closer still. It was a dream! It wasn’t true! It wasn’t the same old man at all. Ah, how horrible! The little governess stared at him in terror. “No, no, no!” she stammered, struggling out of his hands. “One little kiss. A kiss. What is it? Just a kiss, dear little Fräulein. A kiss.” He pushed his face forward, his lips smiling broadly; and how his little blue eyes gleamed behind the spectacles! “Never—never. How can you!” She sprang up, but he was too quick and he held her against the wall, pressed against her his hard old body and his twitching knee and, though she shook her head from side to side, distracted, kissed her on the mouth. On the mouth! Where not a soul who wasn’t a near relation had ever kissed her before. . . .
  • 70. She ran, ran down the street until she found a broad road with tram lines and a policeman standing in the middle like a clockwork doll. “I want to get a tram to the Hauptbahnhof,” sobbed the little governess. “Fräulein?” She wrung her hands at him. “The Hauptbahnhof. There—there’s one now,” and while he watched very much surprised, the little girl with her hat on one side, crying without a handkerchief, sprang on to the tram—not seeing the conductor’s eyebrows, nor hearing the hochwohlgebildete Dame talking her over with a scandalized friend. She rocked herself and cried out loud and said “Ah, ah!” pressing her hands to her mouth. “She has been to the dentist,” shrilled a fat old woman, too stupid to be uncharitable. “Na, sagen Sie ’mal, what toothache! The child hasn’t one left in her mouth.” While the tram swung and jangled through a world full of old men with twitching knees. When the little governess reached the hall of the Hotel Grunewald the same waiter who had come into her room in the morning was standing by table, polishing a tray of glasses. The sight of the little governess seemed to fill him out with some inexplicable important content. He was ready for her question; his answer came pat and suave. “Yes, Fräulein, the lady has been here. I told her that you had arrived and gone out again immediately with a gentleman. She asked me when you were coming back again—but of course I could not say. And then she went to the manager.” He took up a glass from the table, held it up to the light, looked at it with one eye closed, and started polishing it with a corner of his apron. “. . . ?” “Pardon, Fräulein? Ach, no, Fräulein. The manager could tell her nothing— nothing.” He shook his head and smiled at the brilliant glass. “Where is the lady now?” asked the little governess, shuddering so violently that she had to hold her handkerchief up to her mouth. “How should I know?” cried the waiter, and as he swooped past her to pounce upon a new arrival his heart beat so hard against his ribs that he nearly chuckled aloud. “That’s it! that’s it!” he thought. “That will show her.” And as he swung the new arrival’s box on to his shoulders —hoop!—as though he were a giant and the box a feather, he
  • 71. minced over again the little governess’s words, “Gehen Sie. Gehen Sie sofort. Shall I! Shall I!” he shouted to himself.
  • 72. Revelations From eight o’clock in the morning until about half-past eleven Monica Tyrell suffered from her nerves, and suffered so terribly that these hours were—agonizing, simply. It was not as though she could control them. “Perhaps if I were ten years younger . . .” she would say. For now that she was thirty-three she had queer little way of referring to her age on all occasions, of looking at her friends with grave, childish eyes and saying: “Yes, I remember how twenty years ago . . .” or of drawing Ralph’s attention to the girls—real girls—with lovely youthful arms and throats and swift hesitating movements who sat near them in restaurants. “Perhaps if I were ten years younger . . .” “Why don’t you get Marie to sit outside your door and absolutely forbid anybody to come near your room until you ring your bell?” “Oh, if it were as simple as that!” She threw her little gloves down and pressed her eyelids with her fingers in the way he knew so well. “But in the first place I’d be so conscious of Marie sitting there, Marie shaking her finger at Rudd and Mrs. Moon, Marie as a kind of cross between a wardress and a nurse for mental cases! And then, there’s the post. One can’t get over the fact that the post comes, and once it has come, who—who—could wait until eleven for the letters?” His eyes grew bright; he quickly, lightly clasped her. “My letters, darling?” “Perhaps,” she drawled, softly, and she drew her hand over his reddish hair, smiling too, but thinking: “Heavens! What a stupid thing to say!”
  • 73. But this morning she had been awakened by one great slam of the front door. Bang. The flat shook. What was it? She jerked up in bed, clutching the eiderdown; her heart beat. What could it be? Then she heard voices in the passage. Marie knocked, and, as the door opened, with a sharp tearing rip out flew the blind and the curtains, stiffening, flapping, jerking. The tassel of the blind knocked— knocked against the window. “Eh-h, voilà!” cried Marie, setting down the tray and running. “C’est le vent, Madame. C’est un vent insupportable.” Up rolled the blind; the window went up with a jerk; a whitey- greyish light filled the room. Monica caught a glimpse of a huge pale sky and a cloud like a torn shirt dragging across before she hid her eyes with her sleeve. “Marie! the curtains! Quick, the curtains!” Monica fell back into the bed and then “Ring-ting-a-ping-ping, ring-ting-a-ping-ping.” It was the telephone. The limit of her suffering was reached; she grew quite calm. “Go and see, Marie.” “It is Monsieur. To know if Madame will lunch at Princes’ at one- thirty to-day.” Yes, it was Monsieur himself. Yes, he had asked that the message be given to Madame immediately. Instead of replying, Monica put her cup down and asked Marie in a small wondering voice what time it was. It was half-past nine. She lay still and half closed her eyes. “Tell Monsieur I cannot come,” she said gently. But as the door shut, anger—anger suddenly gripped her close, close, violent, half strangling her. How dared he? How dared Ralph do such a thing when he knew how agonizing her nerves were in the morning! Hadn’t she explained and described and even—though lightly, of course; she couldn’t say such a thing directly—given him to understand that this was the one unforgivable thing. And then to choose this frightful windy morning. Did he think it was just a fad of hers, a little feminine folly to be laughed at and tossed aside? Why, only last night she had said: “Ah, but you must take me seriously, too.” And he had replied: “My darling, you’ll not believe me, but I know you infinitely better than you know yourself. Every delicate thought and feeling I bow to, I treasure. Yes, laugh! I
  • 74. love the way your lip lifts”—and he had leaned across the table—“I don’t care who sees that I adore all of you. I’d be with you on mountain-top and have all the searchlights of the world play upon us.” “Heavens!” Monica almost clutched her head. Was it possible he had really said that? How incredible men were! And she had loved him—how could she have loved a man who talked like that. What had she been doing ever since that dinner party months ago, when he had seen her home and asked if he might come and “see again that slow Arabian smile”? Oh, what nonsense—what utter nonsense —and yet she remembered at the time a strange deep thrill unlike anything she had ever felt before. “Coal! Coal! Coal! Old iron! Old iron! Old iron!” sounded from below. It was all over. Understand her? He had understood nothing. That ringing her up on a windy morning was immensely significant. Would he understand that? She could almost have laughed. “You rang me up when the person who understood me simply couldn’t have.” It was the end. And when Marie said: “Monsieur replied he would be in the vestibule in case Madame changed her mind,” Monica said: “No, not verbena, Marie. Carnations. Two handfuls.” A wild white morning, a tearing, rocking wind. Monica sat down before the mirror. She was pale. The maid combed back her dark hair—combed it all back—and her face was like a mask, with pointed eyelids and dark red lips. As she stared at herself in the blueish shadowy glass she suddenly felt—oh, the strangest, most tremendous excitement filling her slowly, slowly, until she wanted to fling out her arms, to laugh, to scatter everything, to shock Marie, to cry: “I’m free. I’m free. I’m free as the wind.” And now all this vibrating, trembling, exciting, flying world was hers. It was her kingdom. No, no, she belonged to nobody but Life. “That will do, Marie,” she stammered. “My hat, my coat, my bag. And now get me a taxi.” Where was she going? Oh, anywhere. She could not stand this silent flat, noiseless Marie, this ghostly, quiet, feminine interior. She must be out; she must be driving quickly— anywhere, anywhere.
  • 75. “The taxi is there, Madame.” As she pressed open the big outer doors of the flats the wild wind caught her and floated her across the pavement. Where to? She got in, and smiling radiantly at the cross, cold-looking driver, she told him to take her to her hairdresser’s. What would she have done without her hairdresser? Whenever Monica had nowhere else to go to or nothing on earth to do she drove there. She might just have her hair waved, and by that time she’d have thought out a plan. The cross, cold driver drove at a tremendous pace, and she let herself be hurled from side to side. She wished he would go faster and faster. Oh, to be free of Princes’ at one-thirty, of being the tiny kitten in the swansdown basket, of being the Arabian, and the grave, delighted child and the little wild creature. . . . “Never again,” she cried aloud, clenching her small fist. But the cab had stopped, and the driver was standing holding the door open for her. The hairdresser’s shop was warm and glittering. It smelled of soap and burnt paper and wallflower brilliantine. There was Madame behind the counter, round, fat, white, her head like a powder-puff rolling on a black satin pin-cushion. Monica always had the feeling that they loved her in this shop and understood her—the real her— far better than many of her friends did. She was her real self here, and she and Madame had often talked—quite strangely—together. Then there was George who did her hair, young, dark, slender George. She was really fond of him. But to-day—how curious! Madame hardly greeted her. Her face was whiter than ever, but rims of bright red showed round her blue bead eyes, and even the rings on her pudgy fingers did not flash. They were cold, dead, like chips of glass. When she called through the wall-telephone to George there was a note in her voice that had never been there before. But Monica would not believe this. No, she refused to. It was just her imagination. She sniffed greedily the warm, scented air, and passed behind the velvet curtain into the small cubicle. Her hat and jacket were off and hanging from the peg, and still George did not come. This was the first time he had ever not been
  • 76. there to hold the chair for her, to take her hat and hang up her bag, dangling it in his fingers as though it were something he’d never seen before—something fairy. And how quiet the shop was! There was not a sound even from Madame. Only the wind blew, shaking the old house; the wind hooted, and the portraits of Ladies of the Pompadour Period looked down and smiled, cunning and sly. Monica wished she hadn’t come. Oh, what a mistake to have come! Fatal. Fatal. Where was George? If he didn’t appear the next moment she would go away. She took off the white kimono. She didn’t want to look at herself any more. When she opened a big pot of cream on the glass shelf her fingers trembled. There was a tugging feeling at her heart as though her happiness—her marvellous happiness—were trying to get free. “I’ll go. I’ll not stay.” She took down her hat. But just at that moment steps sounded, and, looking in the mirror, she saw George bowing in the doorway. How queerly he smiled! It was the mirror of course. She turned round quickly. His lips curled back in a sort of grin, and—wasn’t he unshaved?—he looked almost green in the face. “Very sorry to have kept you waiting,” he mumbled, sliding, gliding forward. Oh, no, she wasn’t going to stay. “I’m afraid,” she began. But he had lighted the gas and laid the tongs across, and was holding out the kimono. “It’s a wind,” he said. Monica submitted. She smelled his fresh young fingers pinning the jacket under her chin. “Yes, there is a wind,” said she, sinking back into the chair. And silence fell. George took out the pins in his expert way. Her hair tumbled back, but he didn’t hold it as he usually did, as though to feel how fine and soft and heavy it was. He didn’t say it “was in a lovely condition.” He let it fall, and, taking a brush out of a drawer, he coughed faintly, cleared his throat and said dully: “Yes, it’s a pretty strong one, I should say it was.”
  • 77. She had no reply to make. The brush fell on her hair. Oh, oh, how mournful, how mournful! It fell quick and light, it fell like leaves; and then it fell heavy, tugging like the tugging at her heart. “That’s enough,” she cried, shaking herself free. “Did I do it too much?” asked George. He crouched over the tongs. “I’m sorry.” There came the smell of burnt paper—the smell she loved—and he swung the hot tongs round in his hand, staring before him. “I shouldn’t be surprised if it rained.” He took up a piece of her hair, when—she couldn’t bear it any longer—she stopped him. She looked at him; she saw herself looking at him in the white kimono like a nun. “Is there something the matter here? Has something happened?” But George gave a half shrug and a grimace. “Oh, no, Madame. Just a little occurrence.” And he took up the piece of hair again. But, oh, she wasn’t deceived. That was it. Something awful had happened. The silence—really, the silence seemed to come drifting down like flakes of snow. She shivered. It was cold in the little cubicle, all cold and glittering. The nickel taps and jets and sprays looked somehow almost malignant. The wind rattled the window-frame; a piece of iron banged, and the young man went on changing the tongs, crouching over her. Oh, how terrifying Life was, thought Monica. How dreadful. It is the loneliness which is so appalling. We whirl along like leaves, and nobody knows—nobody cares where we fall, in what black river we float away. The tugging feeling seemed to rise into her throat. It ached, ached; she longed to cry. “That will do,” she whispered. “Give me the pins.” As he stood beside her, so submissive, so silent, she nearly dropped her arms and sobbed. She couldn’t bear any more. Like a wooden man the gay young George still slid, glided, handed her her hat and veil, took the note, and brought back the change. She stuffed it into her bag. Where was she going now? George took a brush. “There is a little powder on your coat,” he murmured. He brushed it away. And then suddenly he raised himself and, looking at Monica, gave a strange wave with the brush and said: “The truth is, Madame, since you are an old customer—my little daughter died this morning. A first child”—and then his white
  • 78. face crumpled like paper, and he turned his back on her and began brushing the cotton kimono. “Oh, oh,” Monica began to cry. She ran out of the shop into the taxi. The driver, looking furious, swung off the seat and slammed the door again. “Where to?” “Princes’,” she sobbed. And all the way there she saw nothing but a tiny wax doll with a feather of gold hair, lying meek, its tiny hands and feet crossed. And then just before she came to Princes’ she saw a flower shop full of white flowers. Oh, what a perfect thought. Lilies-of-the-valley, and white pansies, double white violets and white velvet ribbon. . . . From an unknown friend. . . . From one who understands. . . . For a Little Girl. . . . She tapped against the window, but the driver did not hear; and, anyway, they were at Princes’ already.
  • 79. The Escape It was his fault, wholly and solely his fault, that they had missed the train. What if the idiotic hotel people had refused to produce the bill? Wasn’t that simply because he hadn’t impressed upon the waiter at lunch that they must have it by two o’clock? Any other man would have sat there and refused to move until they handed it over. But no! His exquisite belief in human nature had allowed him to get up and expect one of those idiots to bring it to their room. . . . And then, when the voiture did arrive, while they were still (Oh, Heavens!) waiting for change, why hadn’t he seen to the arrangement of the boxes so that they could, at least, have started the moment the money had come? Had he expected her to go outside, to stand under the awning in the heat and point with her parasol? Very amusing picture of English domestic life. Even when the driver had been told how fast he had to drive he had paid no attention whatsoever—just smiled. “Oh,” she groaned, “if she’d been a driver she couldn’t have stopped smiling herself at the absurd, ridiculous way he was urged to hurry.” And she sat back and imitated his voice: “Allez, vite, vite”—and begged the driver’s pardon for troubling him. . . . And then the station—unforgettable—with the sight of the jaunty little train shuffling away and those hideous children waving from the windows. “Oh, why am I made to bear these things? Why am I exposed to them? . . .” The glare, the flies, while they waited, and he and the stationmaster put their heads together over the time- table, trying to find this other train, which, of course, they wouldn’t catch. The people who’d gathered round, and the woman who’d held up that baby with that awful, awful head. . . . “Oh, to care as I care
  • 80. —to feel as I feel, and never to be saved anything—never to know for one moment what it was to . . . to . . .” Her voice had changed. It was shaking now—crying now. She fumbled with her bag, and produced from its little maw a scented handkerchief. She put up her veil and, as though she were doing it for somebody else, pitifully, as though she were saying to somebody else: “I know, my darling,” she pressed the handkerchief to her eyes. The little bag, with its shiny, silvery jaws open, lay on her lap. He could see her powder-puff, her rouge stick, a bundle of letters, a phial of tiny black pills like seeds, a broken cigarette, a mirror, white ivory tablets with lists on them that had been heavily scored through. He thought: “In Egypt she would be buried with those things.” They had left the last of the houses, those small straggling houses with bits of broken pot flung among the flower-beds and half-naked hens scratching round the doorsteps. Now they were mounting a long steep road that wound round the hill and over into the next bay. The horses stumbled, pulling hard. Every five minutes, every two minutes the driver trailed the whip across them. His stout back was solid as wood; there were boils on his reddish neck, and he wore a new, a shining new straw hat. . . . There was a little wind, just enough wind to blow to satin the new leaves on the fruit trees, to stroke the fine grass, to turn to silver the smoky olives—just enough wind to start in front of the carriage a whirling, twirling snatch of dust that settled on their clothes like the finest ash. When she took out her powder-puff the powder came flying over them both. “Oh, the dust,” she breathed, “the disgusting, revolting dust.” And she put down her veil and lay back as if overcome. “Why don’t you put up your parasol?” he suggested. It was on the front seat, and he leaned forward to hand it to her. At that she suddenly sat upright and blazed again. “Please leave my parasol alone! I don’t want my parasol! And anyone who was not utterly insensitive would know that I’m far, far
  • 81. too exhausted to hold up a parasol. And with a wind like this tugging at it. . . . Put it down at once,” she flashed, and then snatched the parasol from him, tossed it into the crumpled hood behind, and subsided, panting. Another bend of the road, and down the hill there came a troop of little children, shrieking and giggling, little girls with sun-bleached hair, little boys in faded soldiers’ caps. In their hands they carried flowers—any kind of flowers—grabbed by the head, and these they offered, running beside the carriage. Lilac, faded lilac, greeny-white snowballs, one arum lily, a handful of hyacinths. They thrust the flowers and their impish faces into the carriage; one even threw into her lap a bunch of marigolds. Poor little mice! He had his hand in his trouser pocket before her. “For Heaven’s sake don’t give them anything. Oh, how typical of you! Horrid little monkeys! Now they’ll follow us all the way. Don’t encourage them; you would encourage beggars”; and she hurled the bunch out of the carriage with, “Well, do it when I’m not there, please.” He saw the queer shock on the children’s faces. They stopped running, lagged behind, and then they began to shout something, and went on shouting until the carriage had rounded yet another bend. “Oh, how many more are there before the top of the hill is reached? The horses haven’t trotted once. Surely it isn’t necessary for them to walk the whole way.” “We shall be there in a minute now,” he said, and took out his cigarette-case. At that she turned round towards him. She clasped her hands and held them against her breast; her dark eyes looked immense, imploring, behind her veil; her nostrils quivered, she bit her lip, and her head shook with a little nervous spasm. But when she spoke, her voice was quite weak and very, very calm. “I want to ask you something. I want to beg something of you,” she said. “I’ve asked you hundreds and hundreds of times before, but you’ve forgotten. It’s such a little thing, but if you knew what it meant to me. . . .” She pressed her hands together. “But you can’t
  • 82. know. No human creature could know and be so cruel.” And then, slowly, deliberately, gazing at him with those huge, sombre eyes: “I beg and implore you for the last time that when we are driving together you won’t smoke. If you could imagine,” she said, “the anguish I suffer when that smoke comes floating across my face. . . .” “Very well,” he said. “I won’t. I forgot.” And he put the case back. “Oh, no,” said she, and almost began to laugh, and put the back of her hand across her eyes. “You couldn’t have forgotten. Not that.” The wind came, blowing stronger. They were at the top of the hill. “Hoy-yip-yip-yip,” cried the driver. They swung down the road that fell into a small valley, skirted the sea coast at the bottom of it, and then coiled over a gentle ridge on the other side. Now there were houses again, blue-shuttered against the heat, with bright burning gardens, with geranium carpets flung over the pinkish walls. The coast-line was dark; on the edge of the sea a white silky fringe just stirred. The carriage swung down the hill, bumped, shook. “Yi-ip,” shouted the driver. She clutched the sides of the seat, she closed her eyes, and he knew she felt this was happening on purpose; this swinging and bumping, this was all done—and he was responsible for it, somehow—to spite her because she had asked if they couldn’t go a little faster. But just as they reached the bottom of the valley there was one tremendous lurch. The carriage nearly overturned, and he saw her eyes blaze at him, and she positively hissed, “I suppose you are enjoying this?” They went on. They reached the bottom of the valley. Suddenly she stood up. “Cocher! Cocher! Arrêtez-vous!” She turned round and looked into the crumpled hood behind. “I knew it,” she exclaimed. “I knew it. I heard it fall, and so did you, at that last bump.” “What? Where?” “My parasol. It’s gone. The parasol that belonged to my mother. The parasol that I prize more than—more than . . .” She was simply beside herself. The driver turned round, his gay, broad face smiling.
  • 83. “I, too, heard something,” said he, simply and gaily. “But I thought as Monsieur and Madame said nothing . . .” “There. You hear that. Then you must have heard it too. So that accounts for the extraordinary smile on your face. . . .” “Look here,” he said, “it can’t be gone. If it fell out it will be there still. Stay where you are. I’ll fetch it.” But she saw through that. Oh, how she saw through it! “No, thank you.” And she bent her spiteful, smiling eyes upon him, regardless of the driver. “I’ll go myself. I’ll walk back and find it, and trust you not to follow. For”—knowing the driver did not understand, she spoke softly, gently—“if I don’t escape from you for a minute I shall go mad.” She stepped out of the carriage. “My bag.” He handed it to her. “Madame prefers . . .” But the driver had already swung down from his seat, and was seated on the parapet reading a small newspaper. The horses stood with hanging heads. It was still. The man in the carriage stretched himself out, folded his arms. He felt the sun beat on his knees. His head was sunk on his breast. “Hish, hish,” sounded from the sea. The wind sighed in the valley and was quiet. He felt himself, lying there, a hollow man, a parched, withered man, as it were, of ashes. And the sea sounded, “Hish, hish.” It was then that he saw the tree, that he was conscious of its presence just inside a garden gate. It was an immense tree with a round, thick silver stem and a great arc of copper leaves that gave back the light and yet were sombre. There was something beyond the tree—a whiteness, a softness, an opaque mass, half-hidden— with delicate pillars. As he looked at the tree he felt his breathing die away and he became part of the silence. It seemed to grow, it seemed to expand in the quivering heat until the great carved leaves hid the sky, and yet it was motionless. Then from within its depths or from beyond there came the sound of a woman’s voice. A woman was singing. The warm untroubled voice floated upon the air, and it was all part of the silence as he was part of it. Suddenly, as the
  • 84. voice rose, soft, dreaming, gentle, he knew that it would come floating to him from the hidden leaves and his peace was shattered. What was happening to him? Something stirred in his breast. Something dark, something unbearable and dreadful pushed in his bosom, and like a great weed it floated, rocked . . . it was warm, stifling. He tried to struggle to tear at it, and at the same moment— all was over. Deep, deep, he sank into the silence, staring at the tree and waiting for the voice that came floating, falling, until he felt himself enfolded. . . . . . In the shaking corridor of the train. It was night. The train rushed and roared through the dark. He held on with both hands to the brass rail. The door of their carriage was open. “Do not disturb yourself, Monsieur. He will come in and sit down when he wants to. He likes—he likes—it is his habit. . . . Oui, Madame, je suis un peu souffrante. . . . Mes nerfs. Oh, but my husband is never so happy as when he is travelling. He likes roughing it. . . . My husband. . . . My husband. . . .” The voices murmured, murmured. They were never still. But so great was his heavenly happiness as he stood there he wished he might live for ever.
  • 85. Transcriber’s Note Images of the source text used in this transcription are available through the Internet Archive. The following changes to the text were noted: p. 2: Two subdued chirrups: “Thank you, Mrs. Samuel Josephs”— Added a period after “Josephs”. p. 3: The buggy tiwnkled away in the sunlight—Changed “tiwnkled” to “twinkled”. p. 14: lifted up his oat tails.—Changed “oat” to “coat”. p. 101: the garçon was hauing up the boxes—Changed “hauing” to "hauling". p. 169: I have sung that music many times.”—Inserted a closing single quotation mark before the closing double quotation mark. p. 154: It doesn’t matter at all, darling.” said the good friend.— Changed period after “darling” to a comma. p. 187: “That,” she said, “is most becoming,”—Comma after “becoming” changed to a period. p. 190: opening the French window to let Klaymongso into the garden, cries.—Changed the period after “cries” to a colon. p. 201: What a genius Mr Peacock was.—Inserted a period after “Mr”. p. 202: There she was—off again Now she—Inserted a period after “again”. p. 210: “That's where the ice pudding is to be,” said Cook—Added a period to the end of the sentence.
  • 86. p. 215: “I’m hanged if I won’t,” cried Father. I won’t—Inserted an opening double quotation mark between “Father.” and “I won’t”. p. 258: “I think I ought to gonow.”—Divided “gonow” into two words.
  • 87. *** END OF THE PROJECT GUTENBERG EBOOK BLISS, AND OTHER STORIES *** Updated editions will replace the previous one—the old editions will be renamed. Creating the works from print editions not protected by U.S. copyright law means that no one owns a United States copyright in these works, so the Foundation (and you!) can copy and distribute it in the United States without permission and without paying copyright royalties. Special rules, set forth in the General Terms of Use part of this license, apply to copying and distributing Project Gutenberg™ electronic works to protect the PROJECT GUTENBERG™ concept and trademark. Project Gutenberg is a registered trademark, and may not be used if you charge for an eBook, except by following the terms of the trademark license, including paying royalties for use of the Project Gutenberg trademark. If you do not charge anything for copies of this eBook, complying with the trademark license is very easy. You may use this eBook for nearly any purpose such as creation of derivative works, reports, performances and research. Project Gutenberg eBooks may be modified and printed and given away—you may do practically ANYTHING in the United States with eBooks not protected by U.S. copyright law. Redistribution is subject to the trademark license, especially commercial redistribution. START: FULL LICENSE
  • 88. THE FULL PROJECT GUTENBERG LICENSE
  • 89. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com