1. Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.com
Object-Oriented Python 1st Edition Irv Kalb
https://ebookmeta.com/product/object-oriented-python-1st-
edition-irv-kalb/
OR CLICK HERE
DOWLOAD EBOOK
Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com
2. Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.
Object-Oriented Python 1st Edition Irv Kalb
https://ebookmeta.com/product/object-oriented-python-1st-edition-irv-
kalb/
ebookmeta.com
Object-Oriented Python: Master OOP by Building Games and
GUIs 1st Edition Irv Kalb
https://ebookmeta.com/product/object-oriented-python-master-oop-by-
building-games-and-guis-1st-edition-irv-kalb/
ebookmeta.com
Python 3 Object oriented Programming Building robust and
maintainable software with object oriented design patterns
in Python 2nd Edition Phillips
https://ebookmeta.com/product/python-3-object-oriented-programming-
building-robust-and-maintainable-software-with-object-oriented-design-
patterns-in-python-2nd-edition-phillips/
ebookmeta.com
The World Series Allan Morey
https://ebookmeta.com/product/the-world-series-allan-morey/
ebookmeta.com
3. Monkey King Volume 11 Fight to the Death 1st Edition Wei
Dong Chen Chao Peng
https://ebookmeta.com/product/monkey-king-volume-11-fight-to-the-
death-1st-edition-wei-dong-chen-chao-peng/
ebookmeta.com
Tribe Master 3 A Fantasy Harem Adventure 1st Edition Noah
Layton
https://ebookmeta.com/product/tribe-master-3-a-fantasy-harem-
adventure-1st-edition-noah-layton/
ebookmeta.com
Delivering on the Promise of Democracy Visual Case Studies
in Educational Equity and Transformation 1st Edition
Sukhwant Jhaj
https://ebookmeta.com/product/delivering-on-the-promise-of-democracy-
visual-case-studies-in-educational-equity-and-transformation-1st-
edition-sukhwant-jhaj/
ebookmeta.com
Introducing Translation Studies Theories and Applications
5th Edition Jeremy Munday
https://ebookmeta.com/product/introducing-translation-studies-
theories-and-applications-5th-edition-jeremy-munday/
ebookmeta.com
Framing the Sexual Subject The Politics of Gender
Sexuality and Power Richard Parker (Editor)
https://ebookmeta.com/product/framing-the-sexual-subject-the-politics-
of-gender-sexuality-and-power-richard-parker-editor/
ebookmeta.com
4. Global Politics A New Introduction 3rd Edition Jenny
Edkins Editor Maja Zehfuss Editor
https://ebookmeta.com/product/global-politics-a-new-introduction-3rd-
edition-jenny-edkins-editor-maja-zehfuss-editor/
ebookmeta.com
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
19. 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.
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 explanations of concepts. They were also
extremely helpful in adding and removing commas [do I need one here?]
23. 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 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-
25. 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, 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.
27. 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.
28. 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
29. 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.
30. 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.
31. 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
32. 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!
33. 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.
34. 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
35. 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
36. 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):
37. 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']
38. 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
39. 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
40. 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
41. # 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
42. 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.
43. 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):
44. 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':
46. astronomers, who, in the plain of Sennaar, measured two degrees of
its circumference.
The victorious arms of the Saracens carried into Spain the
learning, as well as the gallantry, of the East; and along with it, the
tables of Almamon, and the Arabian translations of Ptolemy and
Aristotle; and thus Europe received a second time, from Babylon, the
rudiments of the science of the heavens. The writings of Ptolemy
were translated from Arabic into Latin; and the Peripatetic
philosophy was studied in Averroes and Avicenna with as much
eagerness and as much submission to its doctrines in the West, as it
had been in the East.
The doctrine of the Solid Spheres had, originally, been invented, in
order to give a physical account of the revolutions of the heavenly
bodies, according to the system of Concentric Circles, to which that
doctrine was very easily accommodated. Those mathematicians who
invented the doctrine of Eccentric Circles and Epicycles, contented
themselves with showing, how, by supposing the heavenly bodies to
revolve in such orbits, the phenomena might be connected together,
355 and some sort of uniformity and coherence be bestowed upon
their real motions. The physical causes of those motions they left to
the consideration of the philosophers; though, as appears from some
passages of Ptolemy, they had some general apprehension, that they
were to be explained by a like hypothesis. But, though the system of
Hipparchus was adopted by all astronomers and mathematicians, it
never was received, as we have already observed, by any one sect
of philosophers among the ancients. No attempt, therefore, seems to
have been made amongst them, to accommodate to it any such
hypothesis.
47. The schoolmen, who received, at once, from the Arabians, the
philosophy of Aristotle, and the astronomy of Hipparchus, were
necessarily obliged to reconcile them to one another, and to connect
together the revolutions of the Eccentric Circles and Epicycles of the
one, by the solid Spheres of the other. Many different attempts of
this kind were made by many different philosophers: but, of them
all, that of Purbach, in the fifteenth century, was the happiest and
the most esteemed. Though his hypothesis is the simplest of any of
them, it would be in vain to describe it without a scheme; neither is
it easily intelligible with one; for, if the system of Eccentric Circles
and Epicycles was before too perplexed and intricate for the
imagination to rest in it with complete tranquillity and satisfaction, it
became much more so, when this addition had been made to it. The
world, justly indeed, applauded the ingenuity of that philosopher,
who could unite, so happily, two such seemingly inconsistent
systems. His labours, however, seem rather to have increased than
to have diminished the causes of that dissatisfaction, which the
learned soon began to feel with the system of Ptolemy. He, as well
as all those who had worked upon the same plan before, by
rendering this account of things more complex, rendered it more
embarrassing than it had been before.
Neither was the complexness of this system the sole cause of the
dissatisfaction, which the world in general began, soon after the
days of Purbach, to express for it. The tables of Ptolemy having,
upon account of the inaccuracy of the observations on which they
were founded, become altogether wide of the real situation of the
heavenly bodies, those of Almamon, in the ninth century, were, upon
the same hypothesis, composed to correct their deviations. These
again, a few ages afterwards, became, for the same reason, equally
useless. In the thirteenth century, Alphonsus, the philosophical King
48. of Castile, found it necessary to give orders for the composition of
those tables, which bear his name. It is he, who is so well known for
the whimsical impiety of using to say, that, had he been consulted at
the creation of the universe, he could have given good advice; an
apophthegm which is supposed to have proceeded from his dislike to
the intricate system of Ptolemy. In the fifteenth century, the
deviation of the Alphonsine tables began to be as sensible, as those
of Ptolemy and 356 Almamon had been before. It appeared evident,
therefore, that, though the system of Ptolemy might, in the main, be
true, certain corrections were necessary to be made in it before it
could be brought to correspond with exact precision to the
phenomena. For the revolution of his Eccentric Circles and Epicycles,
supposing them to exist, could not, it was evident, be precisely such
as he represented them; since the revolutions of the heavenly bodies
deviated, in a short time, so widely from what the most exact
calculations, that were founded upon his hypothesis, represented
them. It had plainly, therefore, become necessary to correct, by
more accurate observations, both the velocities and directions of all
the wheels and circles of which his hypothesis is composed. This,
accordingly, was begun by Purbach, and carried on by
Regiomontanus, the disciple, the continuator, and the perfecter of
the system of Purbach; and one, whose untimely death, amidst
innumerable projects for the recovery of old, and the invention and
advancement of new sciences, is, even at this day, to be regretted.
When you have convinced the world, that an established system
ought to be corrected, it is not very difficult to persuade them that it
should be destroyed. Not long, therefore, after the death of
Regiomontanus, Copernicus began to meditate a new system, which
should connect together the new appearances, in a more simple as
well as a more accurate manner, than that of Ptolemy.
49. The confusion, in which the old hypothesis represented the
motions of the heavenly bodies, was, he tells us, what first
suggested to him the design of forming a new system, that these,
the noblest works of nature, might no longer appear devoid of that
harmony and proportion which discover themselves in her meanest
productions. What most of all dissatisfied him, was the notion of the
Equalizing Circle, which, by representing the revolutions of the
Celestial Spheres, as equable only, when surveyed from a point that
was different from their centres, introduced a real inequality into
their motions; contrary to that most natural, and indeed fundamental
idea, with which all the authors of astronomical systems, Plato,
Eudoxus, Aristotle, even Hipparchus and Ptolemy themselves, had
hitherto set out, that the real motions of such beautiful and divine
objects must necessarily be perfectly regular, and go on, in a
manner, as agreeable to the imagination, as the objects themselves
are to the senses. He began to consider, therefore, whether, by
supposing the heavenly bodies to be arranged in a different order
from that in which Aristotle and Hipparchus has placed them, this so
much sought for uniformity might not be bestowed upon their
motions. To discover this arrangement, he examined all the obscure
traditions delivered down to us, concerning every other hypothesis
which the ancients had invented, for the same purpose. He found, in
Plutarch, that some old Pythagoreans had represented the Earth as
revolving in the centre of the universe, like a wheel round its own
axis; and that 357 others, of the same sect, had removed it from the
centre, and represented it as revolving in the Ecliptic like a star
round the central fire. By this central fire, he supposed they meant
the Sun; and though in this he was very widely mistaken, it was, it
seems, upon this interpretation, that he began to consider how such
an hypothesis might be made to correspond to the appearances. The
50. supposed authority of these old philosophers, if it did not originally
suggest to him his system, seems, at least, to have confirmed him in
an opinion, which, it is not improbable, that he had beforehand
other reasons for embracing, notwithstanding what he himself would
affirm to the contrary.
It then occurred to him, that, if the Earth was supposed to revolve
every day round its axis, from west to east, all the heavenly bodies
would appear to revolve, in a contrary direction, from east to west.
The diurnal revolution of the heavens, upon this hypothesis, might
be only apparent; the firmament, which has no other sensible
motion, might be perfectly at rest; while the Sun, the Moon, and the
Five Planets, might have no other movement beside that eastward
revolution, which is peculiar to themselves. That, by supposing the
Earth to revolve with the Planets, round the Sun, in an orbit, which
comprehended within it the orbits of Venus and Mercury, but was
comprehended within those of Mars, Jupiter, and Saturn, he could,
without the embarrassment of Epicycles, connect together the
apparent annual revolutions of the Sun, and the direct, retrograde,
and stationary appearances of the Planets: that while the Earth
really revolved round the Sun on one side of the heavens, the Sun
would appear to revolve round the Earth on the other; that while she
really advanced in her annual course, he would appear to advance
eastward in that movement which is peculiar to himself. That, by
supposing the axis of the Earth to be always parallel to itself, not to
be quite perpendicular, but somewhat inclined to the plane of her
orbit, and consequently to present to the Sun, the one pole when on
the one side of him, and the other when on the other, he would
account for the obliquity of the Ecliptic; the Sun’s seemingly
alternate progression from north to south, and from south to north,
51. the consequent change of the seasons, and different lengths of the
days and nights in the different seasons.
If this new hypothesis thus connected together all these
appearances as happily as that of Ptolemy, there were others which
it connected together much better. The three superior Planets, when
nearly in conjunction with the Sun, appear always at the greatest
distance from the Earth, are smallest, and least sensible to the eye,
and seem to revolve forward in their direct motion with the greatest
rapidity. On the contrary, when in opposition to the Sun, that is,
when in their meridian about midnight, they appear nearest the
Earth, are largest, and most sensible to the eye, and seem to revolve
backwards in their retrograde motion. To explain these appearances,
the system of Ptolemy supposed 358 each of these Planets to be at
the upper part of their several Epicycles, in the one case; and at the
lower, in the other. But it afforded no satisfactory principle of
connection, which could lead the mind easily to conceive how the
Epicycles of those Planets, whose spheres were so distant from the
sphere of the Sun, should thus, if one may say so, keep time to his
motion. The system of Copernicus afforded this easily, and like a
more simple machine, without the assistance of Epicycles, connected
together, by fewer movements, the complex appearances of the
heavens. When the superior Planets appear nearly in conjunction
with the Sun, they are then in the side of their orbits, which is
almost opposite to, and most distant from the Earth, and therefore
appear smallest, and least sensible to the eye. But, as they then
revolve in a direction which is almost contrary to that of the Earth,
they appear to advance forward with double velocity; as a ship, that
sails in a contrary direction to another, appears from that other, to
sail both with its own velocity, and the velocity of that from which it
is seen. On the contrary, when those Planets are in opposition to the
52. Sun, they are on the same side of the Sun with the Earth, are
nearest it, most sensible to the eye, and revolve in the same
direction with it; but, as their revolutions round the Sun are slower
than that of the Earth, they are necessarily left behind by it, and
therefore seem to revolve backwards; as a ship which sails slower
than another, though it sails in the same direction, appears from that
other to sail backwards. After the same manner, by the same annual
revolution of the Earth, he connected together the direct and
retrograde motions of the two inferior Planets, as well as the
stationary appearances of all the Five.
There are some other particular phenomena of the two inferior
Planets, which correspond still better to this system, and still worse
to that of Ptolemy. Venus and Mercury seem to attend constantly
upon the motion of the Sun, appearing, sometimes on the one side,
and sometimes on the other, of that great luminary; Mercury being
almost always buried in his rays, and Venus never receding above
forty-eight degrees from him, contrary to what is observed in the
other three Planets, which are often seen in the opposite side of the
heavens, at the greatest possible distance from the Sun. The system
of Ptolemy accounted for this, by supposing that the centres of the
Epicycles of these two Planets were always in the same line with
those of the Sun and the Earth; that they appeared therefore in
conjunction with the Sun, when either in the upper or lower part of
their Epicycles, and at the greatest distance from him, when in the
sides of them. It assigned, however, no reason why the Epicycles of
these two Planets should observe so different a rule from that which
takes place in those of the other three, nor for the enormous
Epicycle of Venus, whose sides must have been forty-eight degrees
distant from the Sun, while its centre was in conjunction with him,
and whose diameter must have covered 359 more than a quadrant of
53. the Great Circle. But how easily all these appearances coincide with
the hypothesis, which represents those two inferior Planets revolving
round the Sun in orbits comprehended within the orbit of the Earth,
is too obvious to require an explanation.
Thus far did this new account of things render the appearances of
the heavens more completely coherent than had been done by any
of the former systems. It did this, too, by a more simple and
intelligible, as well as more beautiful machinery. It represented the
Sun, the great enlightener of the universe, whose body was alone
larger than all the Planets taken together, as established immovable
in the centre, shedding light and heat on all the worlds that
circulated around him in one uniform direction, but in longer or
shorter periods, according to their different distances. It took away
the diurnal revolution of the firmament, whose rapidity, upon the old
hypothesis, was beyond what even thought could conceive. It not
only delivered the imagination from the embarrassment of Epicycles,
but from the difficulty of conceiving these two opposite motions
going on at the same time, which the system of Ptolemy and
Aristotle bestowed upon all the Planets; I mean, their diurnal
westward, and periodical eastward revolutions. The Earth’s
revolution round its own axis took away the necessity for supposing
the first, and the second was easily conceived when by itself. The
Five Planets, which seem, upon all other systems, to be objects of a
species by themselves, unlike to every thing to which the
imagination has been accustomed, when supposed to revolve along
with the Earth round the Sun, were naturally apprehended to be
objects of the same kind with the Earth, habitable, opaque, and
enlightened only by the rays of the Sun. And thus this hypothesis, by
classing them in the same species of things, with an object that is of
all others the most familiar to us, took off that wonder and that
54. uncertainty which the strangeness and singularity of their
appearance had excited; and thus far, too, better answered the great
end of Philosophy.
Neither did the beauty and simplicity of this system alone
recommend it to the imagination; the novelty and unexpectedness of
that view of nature, which it opened to the fancy, excited more
wonder and surprise than the strangest of those appearances, which
it had been invented to render natural and familiar, and these
sentiments still more endeared it. For, though it is the end of
Philosophy, to allay that wonder, which either the unusual or
seemingly disjointed appearances of nature excite, yet she never
triumphs so much, as when, in order to connect together a few, in
themselves, perhaps, inconsiderable objects, she has, if I may say
so, created another constitution of things, more natural, indeed, and
such as the imagination can more easily attend to, but more new,
more contrary to common opinion and expectation, than any of
those appearances themselves. As, in the instance before us, in
order to connect together some seeming irregularities in the motions
of 360 the Planets, the most inconsiderable objects in the heavens,
and of which the greater part of mankind have no occasion to take
any notice during the whole course of their lives, she has, to talk in
the hyperbolical language of Tycho Brahe, moved the Earth from its
foundations, stopped the revolution of the Firmament, made the Sun
stand still, and subverted the whole order of the Universe.
Such were the advantages of this new hypothesis, as they
appeared to its author, when he first invented it. But, though that
love of paradox, so natural to the learned, and that pleasure, which
they are so apt to take in exciting, by the novelties of their supposed
discoveries, the amazement of mankind, may, notwithstanding what
55. one of his disciples tells us to the contrary, have had its weight in
prompting Copernicus to adopt this system; yet, when he had
completed his Treatise of Revolutions, and began coolly to consider
what a strange doctrine he was about to offer to the world, he so
much dreaded the prejudice of mankind against it, that, by a species
of continence, of all others the most difficult to a philosopher, he
detained it in his closet for thirty years together. At last, in the
extremity of old age, he allowed it to be extorted from him, but he
died as soon as it was printed, and before it was published to the
world.
When it appeared in the world, it was almost universally
disapproved of, by the learned as well as by the ignorant. The
natural prejudices of sense, confirmed by education, prevailed too
much with both, to allow them to give it a fair examination. A few
disciples only, whom he himself had instructed in his doctrine,
received it with esteem and admiration. One of them, Reinholdus,
formed, upon this hypothesis, larger and more accurate astronomical
tables, than what accompanied the Treatise of Revolutions, in which
Copernicus had been guilty of some errors in calculation. It soon
appeared, that these Prutenic Tables, as they were called,
corresponded more exactly with the heavens, than the Tables of
Alphonsus. This ought naturally to have formed a prejudice in favour
of the diligence and accuracy of Copernicus in observing the
heavens. But it ought to have formed none in favour of his
hypothesis; since the same observations, and the result of the same
calculations, might have been accommodated to the system of
Ptolemy, without making any greater alteration in that system than
what Ptolemy had foreseen, and had even foretold should be made.
It formed, however, a prejudice in favour of both, and the learned
began to examine, with some attention, an hypothesis which
56. afforded the easiest methods of calculation, and upon which the
most exact predictions had been made. The superior degree of
coherence, which it bestowed upon the celestial appearances, the
simplicity and uniformity which it introduced into the real directions
and velocities of the Planets, soon disposed many astronomers, first
to favour, and at last to embrace a system, which thus connected
together so happily, 361 the most disjointed of those objects that
chiefly occupied their thoughts. Nor can any thing more evidently
demonstrate, how easily the learned give up the evidence of their
senses to preserve the coherence of the ideas of their imagination,
than the readiness with which this, the most violent paradox in all
philosophy, was adopted by many ingenious astronomers,
notwithstanding its inconsistency with every system of physics then
known in the world, and notwithstanding the great number of other
more real objections, to which, as Copernicus left it, this account of
things was most justly exposed.
It was adopted, however, nor can this be wondered at, by
astronomers only. The learned in all other sciences, continued to
regard it with the same contempt as the vulgar. Even astronomers
were divided about its merit; and many of them rejected a doctrine,
which not only contradicted the established system of Natural
Philosophy, but which, considered astronomically only, seemed, to
them, to labour under several difficulties.
Some of the objections against the motion of the Earth, that were
drawn from the prejudices of sense, the patrons of this system,
indeed, easily enough got over. They represented, that the Earth
might really be in motion, though, to its inhabitants, it seemed to be
at rest; and that the Sun and Fixed Stars might really be at rest,
though from the Earth they seemed to be in motion; in the same
57. manner as a ship, which sails through a smooth sea, seems to those
who are in it, to be at rest, though really in motion; while the
objects which she passes along, seem to be in motion, though really
at rest.
But there were some other objections, which, though grounded
upon the same natural prejudices, they found it more difficult to get
over. The earth had always presented itself to the senses, not only
as at rest, but as inert, ponderous, and even averse to motion. The
imagination had always been accustomed to conceive it as such, and
suffered the greatest violence, when obliged to pursue, and attend
it, in that rapid motion which the system of Copernicus bestowed
upon it. To enforce their objection, the adversaries of this hypothesis
were at pains to calculate the extreme rapidity of this motion. They
represented, that the circumference of the Earth had been computed
to be above twenty-thousand miles: if the Earth, therefore, was
supposed to revolve every day round its axis, every point of it near
the equator would pass over above twenty-three thousand miles in a
day; and consequently, near a thousand miles in an hour, and about
sixteen miles in a minute; a motion more rapid than that of a cannon
ball, or even than the swifter progress of sound. The rapidity of its
periodical revolution was yet more violent than that of its diurnal
rotation. How, therefore, could the imagination ever conceive so
ponderous a body to be naturally endowed with so dreadful a
movement? The Peripatetic Philosophy, the only philosophy then
known in the world, still further confirmed 362 this prejudice. That
philosophy, by a very natural, though, perhaps, groundless
distinction, divided all motion into Natural and Violent. Natural
motion was that which flowed from an innate tendency in the body,
as when a stone fell downwards: Violent motion, that which arose
from external force, and which was, in some measure, contrary to
58. the natural tendency of the body, as when a stone was thrown
upwards, or horizontally. No violent motion could be lasting; for,
being constantly weakened by the natural tendency of the body, it
would soon be destroyed. The natural motion of the Earth, as was
evident in all its parts, was downwards, in a straight line to the
centre; as that of fire and air was upwards, in a straight line from
the centre. It was the heavens only that revolved naturally in a
circle. Neither, therefore, the supposed revolution of the Earth round
its own centre, nor that round the Sun, could be natural motions;
they must therefore be violent, and consequently could be of no
long continuance. It was in vain that Copernicus replied, that gravity
was, probably, nothing else besides a tendency in the different parts
of the same Planet, to unite themselves to one another; that this
tendency took place, probably, in the parts of the other Planets, as
well as in those of the Earth; that it could very well be united with a
circular motion; that it might be equally natural to the whole body of
the Planet, and to every part of it; that his adversaries themselves
allowed, that a circular motion was natural to the heavens, whose
diurnal revolution was infinitely more rapid than even that motion
which he had bestowed upon the Earth; that though a like motion
was natural to the Earth, it would still appear to be at rest to its
inhabitants, and all the parts of it to tend in a straight line to the
centre, in the same manner as at present. But this answer, how
satisfactory soever it may appear to be now, neither did nor could
appear to be satisfactory then. By admitting the distinction betwixt
natural and violent motions, it was founded upon the same
ignorance of mechanical principles with the objection. The systems
of Aristotle and Hipparchus supposed, indeed, the diurnal motion of
the heavenly bodies to be infinitely more rapid than even that
dreadful movement which Copernicus bestowed upon the Earth. But
59. they supposed, at the same time, that those bodies were objects of
a quite different species, from any we are acquainted with, near the
surface of the Earth, and to which, therefore, it was less difficult to
conceive that any sort of motion might be natural. Those objects,
besides, had never presented themselves to the senses, as moving
otherwise, or with less rapidity, than these systems represented
them. The imagination, therefore, could feel no difficulty in following
a representation which the senses had rendered quite familiar to it.
But when the Planets came to be regarded as so many Earths, the
case was quite altered. The imagination had been accustomed to
conceive such objects as tending rather to rest than motion; and this
idea of their natural 363 inertness, encumbered, if one may say so,
and clogged its flight whenever it endeavoured to pursue them in
their periodical courses, and to conceive them as continually rushing
through the celestial spaces, with such violent and unremitting
rapidity.
Nor were the first followers of Copernicus more fortunate in their
answers to some other objections, which were founded indeed in the
same ignorance of the laws of motion, but which, at the same time,
were necessarily connected with that way of conceiving things,
which then prevailed universally in the learned world.
If the earth, it was said, revolved so rapidly from west to east, a
perpetual wind would set in from east to west, more violent than
what blows in the greatest hurricanes; a stone, thrown westwards
would fly to a much greater distance than one thrown with the same
force eastwards; as what moved in a direction, contrary to the
motion of the Earth, would necessarily pass over a greater portion of
its surface, than what, with the same velocity, moved along with it. A
ball, it was said, dropped from the mast of a ship under sail, does
60. not fall precisely at the foot of the mast, but behind it; and in the
same manner, a stone dropped from a high tower would not, upon
the supposition of the Earth’s motion, fall precisely at the bottom of
the tower, but west of it, the Earth being, in the mean time, carried
away eastward from below it. It is amusing to observe, by what,
subtile and metaphysical evasions the followers of Copernicus
endeavoured to elude this objection, which before the doctrine of
the Composition of Motion had been explained by Galileo, was
altogether unanswerable. They allowed, that a ball dropped from the
mast of a ship under sail would not fall at the foot of the mast, but
behind it; because the ball, they said, was no part of the ship, and
because the motion of the ship was natural neither to itself nor to
the ball. But the stone was a part of the earth, and the diurnal and
annual revolutions of the Earth were natural to the whole, and to
every part of it, and therefore to the stone. The stone, therefore,
having naturally the same motion with the Earth, fell precisely at the
bottom of the tower. But this answer could not satisfy the
imagination, which still found it difficult to conceive how these
motions could be natural to the earth; or how a body, which had
always presented itself to the senses as inert, ponderous, and averse
to motion, should naturally be continually wheeling about both its
own axis and the Sun, with such violent rapidity. It was, besides,
argued by Tycho Brahe, upon the principles of the same philosophy
which had afforded both the objection and the answer, that even
upon the supposition, that any such motion was natural to the whole
body of the Earth, yet the stone, which was separated from it, could
no longer be actuated by that motion. The limb, which is cut off
from an animal, loses those animal motions which were natural to
the whole. The branch, which is cut off from the trunk, loses that
vegetative 364 motion which is natural to the whole tree. Even the
61. metals, minerals, and stones, which were dug out from the bosom of
the Earth, lose those motions which occasioned their production and
increase, and which were natural to them in their original state.
Though the diurnal and annual motion of the Earth, therefore, had
been natural to them while they were contained in its bosom, it
could no longer be so when they were separated from it.
Tycho Brahe, the great restorer of the science of the heavens, who
had spent his life, and wasted his fortune upon the advancement of
Astronomy, whose observations were both more numerous and more
accurate than those of all the astronomers who had gone before
him, was himself so much affected by the force of this objection,
that, though he had never mentioned the system of Copernicus
without some note of high admiration he had conceived for its
author, he could never himself be induced to embrace it; yet all his
astronomical observations tended to confirm it. They demonstrated,
that Venus and Mercury were sometimes above, and sometimes
below the Sun; and that, consequently, the Sun, and not the Earth,
was the centre of their periodical revolutions. They showed, that
Mars, when in his meridian at midnight, was nearer to the Earth
than the Earth is to the Sun; though, when in conjunction with the
Sun, he was much more remote from the Earth than that luminary; a
discovery which was absolutely inconsistent with the system of
Ptolemy, which proved, that the Sun, and not the Earth, was the
centre of the periodical revolutions of Mars, as well as of Venus and
Mercury; and which demonstrated that the Earth was placed betwixt
the orbits of Mars and Venus. They made the same thing probable
with regard to Jupiter and Saturn; that they, too, revolved round the
Sun; and that, therefore, the Sun, if not the centre of the universe,
was at least, that of the planetary system. They proved that Comets
were superior to the Moon, and moved through the heavens in all
62. possible directions; an observation incompatible with the Solid
Spheres of Aristotle and Purbach, and which, therefore, overturned
the physical part, at least, of the established systems of Astronomy.
All these observations, joined to his aversion to the system, and
perhaps, notwithstanding the generosity of his character, some little
jealousy for the fame of Copernicus, suggested to Tycho the idea of
a new hypothesis, in which the Earth continued to be, as in the old
account, the immovable centre of the universe, round which the
firmament revolved every day from east to west, and, by some
secret virtue, carried the Sun, the Moon, and the Five Planets along
with it, notwithstanding their immense distance, and
notwithstanding that there was nothing betwixt it and them but the
most fluid ether. But, although all these seven bodies thus obeyed
the diurnal revolution of the Firmament, they had each of them, as
in the old system, too, a 365 contrary periodical eastward revolution
of their own, which made them appear to be every day, more or
less, left behind by the Firmament. The Sun was the centre of the
periodical revolutions of the Five Planets; the Earth, that of the Sun
and Moon. The Five Planets followed the Sun in his periodical
revolution round the Earth, as they did the Firmament in its diurnal
rotation. The three superior Planets comprehended the Earth within
the orbit in which they revolved round the Sun, and had each of
them an Epicycle to connect together, in the same manner as in the
system of Ptolemy, their direct, retrograde, and stationary
appearances. As, notwithstanding their immense distance, they
followed the Sun in his periodical revolution round the Earth, keeping
always at an equal distance from him, they were necessarily brought
much nearer to the Earth when in opposition to the Sun, than than
when in conjunction with him. Mars, the nearest of them, when in
his meridian at midnight, came within the orbit which the Sun
63. described round the Earth, and consequently was then nearer to the
Earth than the Earth was to the Sun. The appearances of the two
inferior Planets were explained, in the same manner, as in the
system of Copernicus, and consequently required no Epicycle to
connect them. The circles in which the Five Planets performed their
periodical revolutions round the Sun, as well as those in which the
Sun and Moon performed theirs round the Earth, were, as both in
the old and new hypothesis, Eccentric Circles, to connect together
their differently accelerated and retarded motions.
Such was the system of Tycho Brahe, compounded, as is evident,
out of these of Ptolemy and Copernicus; happier than that of
Ptolemy, in the account which it gives of the motions of the two
inferior Planets; more complex, by supposing the different
revolutions of all the Five to be performed round two different
centres; the diurnal round the Earth, the periodical round the Sun,
but, in every respect, more complex and more incoherent than that
of Copernicus. Such, however, was the difficulty that mankind felt in
conceiving the motion of the Earth, that it long balanced the
reputation of that otherwise more beautiful system. It may be said,
that those who considered the heavens only, favoured the system of
Copernicus, which connected so happily all the appearances which
presented themselves there; but that those who looked upon the
Earth, adopted the account of Tycho Brahe, which, leaving it at rest
in the centre of the universe, did less violence to the usual habits of
the imagination. The learned were, indeed, sensible of the intricacy,
and of the many incoherences of that system; that it gave no
account why the Sun, Moon, and Five Planets, should follow the
revolution of the Firmament; or why the Five Planets,
notwithstanding the immense distance of the three superior ones,
should obey the periodical motion of the Sun; or why the Earth,
64. though placed between the orbits of Mars and Venus, should remain
immovable in the centre 366 of the Firmament, and constantly resist
the influence of whatever it was, which carried bodies that were so
much larger than itself, and that were placed on all sides of it,
periodically round the Sun. Tycho Brahe died before he had fully
explained his system. His great and merited renown disposed many
of the learned to believe, that, had his life been longer, he would
have connected together many of these incoherences, and knew
methods of adapting his system to some other appearances, with
which none of his followers could connect it.
The objection to the system of Copernicus, which was drawn from
the nature of motion, and that was most insisted on by Tycho Brahe,
was at last fully answered by Galileo; not, however, till about thirty
years after the death of Tycho, and about a hundred after that of
Copernicus. It was then that Galileo, by explaining the nature of the
composition of motion, by showing, both from reason and
experience, that a ball dropped from the mast of a ship under sail
would fall precisely at the foot of the mast, and by rendering this
doctrine, from a great number of other instances, quite familiar to
the imagination, took off, perhaps, the principal objection which had
been made to this hypothesis of the astronomers.
Several other astronomical difficulties, which encumbered this
account of things, were removed by the same philosopher.
Copernicus, after altering the centre of the world, and making the
Earth, and all the Planets revolve round the Sun, was obliged to
leave the Moon to revolve round the Earth as before. But no
example of any such secondary Planet having then been discovered
in the heavens, there seemed still to be this irregularity remaining in
the system. Galileo, who first applied telescopes to Astronomy,
65. discovered, by their assistance, the Satellites of Jupiter, which,
revolving round that Planet, at the same time that they were carried
along with it in its revolution, round either the Earth, or the Sun,
made it seem less contrary to the analogy of nature, that the Moon
should both revolve round the Earth, and accompany her in her
revolution round the Sun.
It had been objected to Copernicus, that, if Venus and Mercury
revolved round the Sun in an orbit comprehended within the orbit of
the Earth, they would show all the same phases with the Moon;
present, sometimes their darkened, and sometimes their enlightened
sides to the Earth, and sometimes part of the one, and part of the
other. He answered, that they undoubtedly did all this; but that their
smallness and distance hindered us from perceiving it. This very bold
assertion of Copernicus was confirmed by Galileo. His telescopes
rendered the phases of Venus quite sensible, and thus
demonstrated, more evidently than had been done, even by the
observations of Tycho Brahe, the revolutions of these two Planets
round the Sun, as well as so far destroyed the system of Ptolemy.
The mountains and seas, which, by the help of the same
instrument, 367 he discovered, or imagined he had discovered in the
Moon, rendering that Planet, in every respect, similar to the Earth,
made it seem less contrary to the analogy of nature, that, as the
Moon revolved round the Earth, the Earth should revolve round the
Sun.
The spots which, in the same manner, he discovered in the Sun,
demonstrating, by their motion, the revolution of the Sun round his
axis, made it seem less improbable that the Earth, a body so much
smaller than the Sun, should likewise revolve round her axis in the
same manner.
66. Succeeding telescopical observations, discovered, in each of the
Five Planets, spots not unlike those which Galileo had observed in
the Moon, and thereby seemed to demonstrate what Copernicus had
only conjectured, that the Planets were naturally opaque,
enlightened only by the rays of the Sun, habitable, diversified by
seas and mountains, and, in every respect, bodies of the same kind
with the earth; and thus added one other probability to this system.
By discovering, too, that each of the Planets revolved round its own
axis, at the same time that it was carried round either the Earth or
the Sun, they made it seem quite agreeable to the analogy of
nature, that the Earth, which, in every other respect, resembled the
Planets, should, like them too, revolve round its own axis, and at the
same time perform its periodical motion round the Sun.
While, in Italy, the unfortunate Galileo was adding so many
probabilities to the system of Copernicus, there was another
philosopher employing himself in Germany, to ascertain, correct, and
improve it; Kepler, with great genius, but without the taste, or the
order and method of Galileo, possessed, like all his other
countrymen, the most laborious industry, joined to that passion for
discovering proportions and resemblances betwixt the different parts
of nature, which, though common to all philosophers, seems, in him,
to have been excessive. He had been instructed, by Mæstlinus, in
the system of Copernicus; and his first curiosity was, as he tells us,
to find out, why the Planets, the Earth being counted for one, were
Six in number; why they were placed at such irregular distances
from the Sun; and whether there was any uniform proportion
betwixt their several distances, and the times employed in their
periodical revolutions. Till some reason, or proportion of this kind,
could be discovered, the system did not appear to him to be
completely coherent. He endeavoured, first, to find it in the
67. proportions of numbers, and plain figures; afterwards, in those of
the regular solids; and, last of all, in those of the musical divisions of
the Octave. Whatever was the science which Kepler was studying,
he seems constantly to have pleased himself with finding some
analogy betwixt it and the system of the universe; and thus,
arithmetic and music, plane and solid geometry, came all of them by
turns to illustrate the doctrine of the Sphere, in the explaining of
which he was, by his 368 profession, principally employed. Tycho
Brahe, to whom he had presented one of his books, though he could
not but disapprove of his system, was pleased, however, with his
genius, and with his indefatigable diligence in making the most
laborious calculations. That generous and magnificent Dane invited
the obscure and indigent Kepler to come and live with him, and
communicated to him, as soon as he arrived, his observations upon
Mars, in the arranging and methodizing of which his disciples were
at that time employed. Kepler, upon comparing them with one
another, found, that the orbit of Mars was not a perfect circle; that
one of its diameters was somewhat longer than the other; and that
it approached to an oval, or an ellipse, which had the Sun placed in
one of its foci. He found, too, that the motion of the Planet was not
equable; that it was swiftest when nearest the Sun, and slowest
when furthest from him; and that its velocity gradually increased, or
diminished, according as it approached or receded from him. The
observations of the same astronomer discovered to him, though not
so evidently, that the same things were true of all the other Planets;
that their orbits were elliptical, and that their motions were swiftest
when nearest the Sun, and slowest when furthest from him. They
showed the same things, too, of the Sun, if supposed to revolve
round the Earth; and consequently of the Earth, if it also was
supposed to revolve round the Sun.
68. That the motions of all the heavenly bodies were perfectly circular,
had been the fundamental idea upon which every astronomical
hypothesis, except the irregular one of the Stoics, had been built. A
circle, as the degree of its curvature is every where the same, is of
all curve lines the simplest and the most easily conceived. Since it
was evident, therefore, that the heavenly bodies did not move in
straight lines, the indolent imagination found, that it could most
easily attend to their motions if they were supposed to revolve in
perfect circles. It had, upon this account, determined that a circular
motion was the most perfect of all motions, and that none but the
most perfect motion could be worthy of such beautiful and divine
objects; and it had upon this account, so often, in vain, endeavoured
to adjust to the appearances, so many different systems, which all
supposed them to revolve in this perfect manner.
The equality of their motions was another fundamental idea,
which, in the same manner, and for the same reason, was supposed
by all the founders of astronomical systems. For an equal motion can
be more easily attended to, than one that is continually either
accelerated or retarded. All inconsistency, therefore, was declared to
be unworthy those bodies which revolved in the celestial regions,
and to be fit only for inferior and sublunary things. The calculations
of Kepler overturned, with regard to the Planets, both these natural
prejudices of the imagination; destroyed their circular orbits; and
introduced into their 369 real motions, such an equality as no
equalizing circle would remedy. It was, however, to render their
motion perfectly equable, without even the assistance of a equalizing
circle, that Copernicus, as he himself assures us, had originally
invented his system. Since the calculations of Kepler, therefore,
overturned what Copernicus had principally in view in establishing
69. his system, we cannot wonder that they should at first seem rather
to embarrass than improve it.
It is true, by these elliptical orbits and unequal motions, Kepler
disengaged the system from the embarrassment of those small
Epicycles, which Copernicus, in order to connect the seemingly
accelerated and retarded movements of the Planets, with their
supposed real equality, had been obliged to leave in it. For it is
remarkable, that though Copernicus had delivered the orbits of the
Planets from the enormous Epicycles of Hipparchus, that though in
this consisted the great superiority of his system above that of the
ancient astronomers, he was yet obliged, himself, to abandon, in
some measure, this advantage, and to make use of some small
Epicycles, to join together those seeming irregularities. His Epicycles
indeed, like the irregularities for whose sake they were introduced,
were but small ones, and the imaginations of his first followers
seem, accordingly, either to have slurred them over altogether, or
scarcely to have observed them. Neither Galileo, nor Gassendi, the
two most eloquent of his defenders, take any notice of them. Nor
does it seem to have been generally attended to, that there was any
such thing as Epicycles in the system of Copernicus, till Kepler, in
order to vindicate his own elliptical orbits, insisted, that even,
according to Copernicus, the body of the Planet was to be found but
at two different places in the circumference of that circle which the
centre of its Epicycle described.
It is true, too, that an ellipse is, of all curve lines after a circle, the
simplest and most easily conceived; and it is true, besides all this,
that, while Kepler took from the motion of the Planets the easiest of
all proportions, that of equality, he did not leave them absolutely
without one, but ascertained the rule by which their velocities
70. continually varied; for a genius so fond of analogies, when he had
taken away one, would be sure to substitute another in its room.
Notwithstanding all this, notwithstanding that his system was better
supported by observations than any system had ever been before,
yet, such was the attachment to the equal motions and circular
orbits of the Planets, that it seems, for some time, to have been in
general but little attended to by the learned, to have been altogether
neglected by philosophers, and not much regarded even by
astronomers.
Gassendi, who began to figure in the world about the latter days
of Kepler, and who was himself no mean astronomer, seems indeed
to have conceived a good deal of esteem for his diligence and
accuracy in accommodating the observations of Tycho Brahe to the
system of 370 Copernicus. But Gassendi appears to have had no
comprehension of the importance of those alterations which Kepler
had made in that system, as is evident from his scarcely ever
mentioning them in the whole course of his voluminous writings
upon Astronomy. Des Cartes, the contemporary and rival of
Gassendi, seems to have paid no attention to them at all, but to
have built his Theory of the Heavens, without any regard to them.
Even those astronomers, whom a serious attention had convinced of
the justness of his corrections, were still so enamoured with the
circular orbits and equal motion, that they endeavoured to
compound his system with those ancient but natural prejudices.
Thus, Ward endeavoured to show that, though the Planets moved in
elliptical orbits, which had the Sun in one of their foci, and though
their velocities in the elliptical line were continually varying, yet, if a
ray was supposed to be extended from the centre of any one of
them to the other focus, and to be carried along by the periodical
motion of the Planet, it would make equal angles in equal times, and
71. consequently cut off equal portions of the circle of which that other
focus was the centre. To one, therefore, placed in that focus, the
motion of the Planet would appear to be perfectly circular and
perfectly equable, in the same manner as in the Equalizing Circles of
Ptolemy and Hipparchus. Thus Bouillaud, who censured this
hypothesis of Ward, invented another of the same kind, infinitely
more whimsical and capricious. The Planets, according to that
astronomer, always revolve in circles; for that being the most perfect
figure, it is impossible they should revolve in any other. No one of
them, however, continues to move in any one circle, but is
perpetually passing from one to another, through an infinite number
of circles, in the course of each revolution; for an ellipse, said he, is
an oblique section of a cone, and in a cone, betwixt the two vortices
of the ellipse there is an infinite number of circles, out of the
infinitely small portions of which the elliptical line is compounded.
The Planet, therefore which moves in this line, is, in every point of it,
moving in an infinitely small portion of a certain circle. The motion of
each Planet, too, according to him, was necessarily, for the same
reason, perfectly equable. An equable motion being the most perfect
of all motions. It was not, however, in the elliptical line, that it was
equable, but in any one of the circles that were parallel to the base
of that cone, by whose section this elliptical line had been formed:
for, if a ray was extended from the Planet to any one of those circles,
and carried along by its periodical motion, it would cut off equal
portions of that circle in equal times; another most fantastical
equalising circle, supported by no other foundation besides the
frivolous connection between a cone and an ellipse, and
recommended by nothing but the natural passion for circular orbits
and equable motions. It may be regarded as the last effort of this
passion, and may serve to show the force of that principle which
72. could 371 thus oblige this accurate observer, and great improver of
the Theory of the Heavens, to adopt so strange an hypothesis. Such
was the difficulty and hesitation with which the followers of
Copernicus adopted the corrections of Kepler.
The rule, indeed, which Kepler ascertained for determining the
gradual acceleration or retardation in the movement of the Planets,
was intricate, and difficult to be comprehended; it could therefore
but little facilitate the progress of the imagination in tracing those
revolutions which were supposed to be conducted by it. According to
that astronomer, if a straight line was drawn from the centre of each
Planet to the Sun, and carried along by the periodical motion of the
Planet, it would describe equal areas in equal times, though the
Planet did not pass over equal spaces; and the same rule he found,
took place nearly with regard to the Moon. The imagination, when
acquainted with the law by which any motion is accelerated or
retarded, can follow and attend to it more easily, than when at a
loss, and, as it were, wandering in uncertainty with regard to the
proportion which regulates its varieties; the discovery of this analogy
therefore, no doubt, rendered the system of Kepler more agreeable
to the natural taste of mankind: it, was, however, an analogy too
difficult to be followed, or comprehended, to render it completely so.
Kepler, besides this, introduced another new analogy into the
system, and first discovered, that there was one uniform relation
observed betwixt the distances of the Planets from the Sun, and the
times employed in their periodical motions. He found, that their
periodical times were greater than in proportion to their distances,
and less than in proportion to the squares of those distances; but,
that they were nearly as the mean proportionals betwixt their
distances and the squares of their distances; or, in other words, that
73. the squares of their periodical times were nearly as the cubes of
their distances; an analogy, which, though, like all others, it no
doubt rendered the system somewhat more distinct and
comprehensible, was, however, as well as the former, of too intricate
a nature to facilitate very much the effort of the imagination in
conceiving it.
The truth of both these analogies, intricate as they were, was at
last fully established by the observations of Cassini. That astronomer
first discovered, that the secondary Planets of Jupiter and Saturn
revolved round their primary ones, according to the same laws which
Kepler had observed in the revolutions of the primary ones round the
Sun, and that of the Moon round the earth; that each of them
described equal areas in equal times, and that the squares of their
periodic times were as the cubes of their distances. When these two
last abstruse analogies, which, when Kepler at first observed them,
were but little regarded, had been thus found to take place in the
revolutions of the Four Satellites of Jupiter, and in those of the Five
of Saturn, they were 372 now thought not only to confirm the
doctrine of Kepler, but to add a new probability to the Copernican
hypothesis. The observations of Cassini seem to establish it as a law
of the system, that, when one body revolved round another, it
described equal areas in equal times; and that, when several
revolved round the same body, the squares of their periodic times
were as the cubes of their distances. If the Earth and the Five
Planets were supposed to revolve round the Sun, these laws, it was
said, would take place universally. But if, according to the system of
Ptolemy, the Sun, Moon, and Five Planets were supposed to revolve
round the Earth, the periodical motions of the Sun and Moon, would,
indeed, observe the first of these laws, would each of them describe
equal areas in equal times; but they would not observe the second,
74. the squares of their periodic times would not be as the cubes of their
distances: and the revolutions of the Five Planets would observe
neither the one law nor the other. Or if, according to the system of
Tycho Brahe, the Five Planets were supposed to revolve round the
Sun, while the Sun and Moon revolved round the Earth, the
revolutions of the Five Planets round the Sun, would, indeed,
observe both these laws; but those of the Sun and Moon round the
Earth would observe only the first of them. The analogy of nature,
therefore, could be preserved completely, according to no other
system but that of Copernicus, which, upon that account, must be
the true one. This argument is regarded by Voltaire, and the Cardinal
of Polignac, as an irrefragable demonstration; even M‘Laurin, who
was more capable of judging, nay, Newton himself, seems to
mention it as one of the principal evidences for the truth of that
hypothesis. Yet, an analogy of this kind, it would seem, far from a
demonstration, could afford, at most, but the shadow of a
probability.
It is true, that though Cassini supposed the Planets to revolve in
an oblong curve, it was in a curve somewhat different from that of
Kepler. In the ellipse, the sum of the two lines which are drawn from
any one point in the circumference to the two foci, is always equal to
that of those which are drawn from any other point in the
circumference to the same foci. In the curve of Cassini, it is not the
sum of the lines, but the rectangles which are contained under the
lines, that are always equal. As this, however, was a proportion more
difficult to be comprehended by astronomers than the other, the
curve of Cassini has never had the vogue.
Nothing now embarrassed the system of Copernicus, but the
difficulty which the imagination felt in conceiving bodies so
75. immensely ponderous as the Earth and the other Planets revolving
round the Sun with such incredible rapidity. It was in vain that
Copernicus pretended, that, notwithstanding the prejudices of sense,
this circular motion might be as natural to the Planets, as it is to a
stone to fall to the ground. The imagination had been accustomed to
conceive such 373 objects as tending rather to rest than motion. This
habitual idea of their natural inertness was incompatible with that of
their natural motion. It was in vain that Kepler, in order to assist the
fancy in connecting together this natural inertness with their
astonishing velocities, talked of some vital and immaterial virtue,
which was shed by the Sun into the surrounding spaces, which was
whirled about with his revolution round his own axis, and which,
taking hold of the Planets, forced them, in spite of their
ponderousness and strong propensity to rest, thus to whirl about the
centre of the system. The imagination had no hold of this immaterial
virtue, and could form no determinate idea of what it consisted in.
The imagination, indeed, felt a gap, or interval, betwixt the constant
motion and the supposed inertness of the Planets, and had in this,
as in all other cases, some general idea or apprehension that there
must be a connecting chain of intermediate objects to link together
these discordant qualities. Wherein this connecting chain consisted,
it was, indeed, at a loss to conceive; nor did the doctrine of Kepler
lend it any assistance in this respect. That doctrine, like almost all
those of the philosophy in fashion during his time, bestowed a name
upon this invisible chain, called it an immaterial virtue, but afforded
no determinate idea of what was its nature.
Des Cartes was the first who attempted to ascertain, precisely,
wherein this invisible chain consisted, and to afford the imagination
a train of intermediate events, which, succeeding each other in an
order that was of all others the most familiar to it, should unite those