Software Design by Example 1st Edition Greg Wilson 2024 scribd download
Software Design by Example 1st Edition Greg Wilson 2024 scribd download
com
https://ebookname.com/product/software-design-by-
example-1st-edition-greg-wilson/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookname.com/product/superspeed-device-design-by-example-1rd-
edition-john-hyde/
ebookname.com
https://ebookname.com/product/swift-by-example-1st-edition-scalzo/
ebookname.com
https://ebookname.com/product/structural-and-evolutionary-genomics-
natural-selection-in-genome-evolution-1st-edition-giorgio-bernardi-
eds/
ebookname.com
Script Culture and the American Screenplay 1st Edition
Kevin Alexander Boon
https://ebookname.com/product/script-culture-and-the-american-
screenplay-1st-edition-kevin-alexander-boon/
ebookname.com
https://ebookname.com/product/allied-axis-the-photo-journal-of-the-
second-world-war-issue-3-1st-edition-patrick-stansell/
ebookname.com
https://ebookname.com/product/does-inflation-in-china-affect-the-
united-states-and-japan-1st-edition-luke-willard/
ebookname.com
https://ebookname.com/product/flight-from-wonder-an-investigation-of-
scientific-creativity-1st-edition-albert-rothenberg/
ebookname.com
https://ebookname.com/product/a-new-humanism-1st-edition-daisaku-
ikeda/
ebookname.com
Software Design by
Example
The best way to learn design in any field is to study examples, and some of the best examples
of software design come from the tools programmers use in their own work. Software De-
sign by Example: A Tool-Based Introduction with Python therefore builds small versions
of the things programmers use in order to demystify them and give some insights into how ex-
perienced programmers think. From a file backup system and a testing framework to a regular
expression matcher, a browser layout engine, and a very small compiler, we explore common
design patterns, show how making code easier to test also makes it easier to re-use, and help
readers understand how debuggers, profilers, package managers, and version control systems
work so that they can use them more effectively.
This material can be used for self-paced study, in an undergraduate course on software design,
or as the core of an intensive weeklong workshop for working programmers. Each chapter has
a set of exercises ranging in size and difficulty from half a dozen lines to a full day’s work. Read-
ers should be familiar with the basics of modern Python, but the more advanced features of the
language are explained and illustrated as they are introduced.
All the written material in this project can be freely re-used under the terms of the Creative
Commons - Attribution license, while all of the software is made available under the terms of
the Hippocratic License. All proceeds from the sale of this book will go to support the Red Door
Family Shelter in Toronto.
Features:
• Teaches software design by showing programmers how to build the tools they use every day
• Each chapter includes exercises to help readers check and deepen their understanding
• All the example code can be downloaded, re-used, and modified under an open license
Dr. Greg Wilson is a programmer, author, and educator based in Toronto. He co-founded and
was the first Executive Director of Software Carpentry, which has taught basic software skills to
tens of thousands of researchers worldwide, and he has authored or edited over a dozen books
(including two for children). Greg is a member of the Python Software Foundation and a recipi-
ent of ACM SIGSOFT’s Influential Educator of the Year Award.
Taylor & Francis
Taylor & Francis Group
http://taylorandfrancis.com
Software Design by
Example
A Tool-Based Introduction with Python
Greg Wilson
First edition published 2024
by CRC Press
2385 NW Executive Center Drive, Suite 320, Boca Raton FL 33431
Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot as-
sume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have
attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders
if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please
write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or
utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including pho-
tocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission
from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the
Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are
not available on CCC please contact mpkbookspermissions@tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for iden-
tification and explanation without intent to infringe.
DOI: 10.1201/9781032725239
Typeset in Arial
by KnowledgeWorks Global Ltd.
Publisher’s note: This book has been prepared from camera-ready copy provided by the authors.
Dedication
1 Introduction 1
1.1 Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 The Big Ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 What People Are Saying . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4 Matching Patterns 25
4.1 Simple Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.2 Rethinking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5 Parsing Text 35
5.1 Tokenizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.2 Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
5.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6 Running Tests 43
6.1 Storing and Running Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.2 Finding Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
6.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
6.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
vii
viii Contents
7 An Interpreter 51
7.1 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
7.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
7.3 Introspection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
7.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
7.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
9 Protocols 69
9.1 Mock Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
9.2 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
9.3 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
9.4 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
9.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
9.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
10 A File Archiver 81
10.1 Saving Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
10.2 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
10.3 Tracking Backups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
10.4 Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
10.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
10.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11 An HTML Validator 91
11.1 HTML and the DOM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
11.2 The Visitor Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
11.3 Checking Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
11.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
11.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
12 A Template Expander 99
12.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
12.2 Managing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
12.3 Visiting Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
12.4 Implementing Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
12.5 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
12.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
12.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
18 A Database 165
18.1 Starting Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
18.2 Saving Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
18.3 A File-Backed Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
18.4 Playing with Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
18.5 Persisting Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
18.6 Cleaning Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
18.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
18.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
26 A Debugger 255
26.1 One Step at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
26.2 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
26.3 Extensibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
26.4 Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
26.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
26.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
27 Conclusion 267
A Bibliography 269
C Syllabus 287
D License 293
D.1 Writing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
D.2 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
F Contributing 299
F.1 Editing Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
F.2 Making Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
F.3 FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
G Glossary 303
Index 327
Taylor & Francis
Taylor & Francis Group
http://taylorandfrancis.com
1
Introduction
• The best way to learn design is to study examples, and the best programs to use as
examples are the ones programmers use every day.
• These lessons assume readers can write small programs and want to write larger
ones, or are looking for material to use in software design classes that they teach.
• All of the content is free to read and re-use under open licenses, and all royalties
from sales of this book will go to charity.
The best way to learn design in any field is to study examples [Schon1984; Petre2016],
and the most approachable examples are ones that readers are already familiar with. These
lessons therefore build small versions of tools that programmers use every day1 to show
how experienced software designers think. Along the way, they introduce some fundamen-
tal ideas in computer science that many self-taught programmers haven’t encountered. We
hope these lessons will help you design better software yourself, and that if you know how
programming tools work, you’ll be more likely to use them and better able to use them well.
1.1 Audience
This learner persona [Wilson2019] describes who this book is for:
Maya has a master’s degree in genomics. She knows enough Python to analyze
data from her experiments, but struggles to write code other people can use. These
lessons will show her how to design, build, and test large programs in less time and
with less pain.
• Write Python programs using lists, loops, conditionals, dictionaries, and functions.
• Puzzle your way through Python programs that use classes and exceptions.
• Use Git2 to save and share files. (It’s OK not to know the more obscure commands3 .)
1 https://en.wikipedia.org/wiki/Programming_tool
2 https://git-scm.com/
3 https://git-man-page-generator.lokaltog.net/
1
2 1 Introduction
2
19 A Build Objects and Running Page 14
Manager Classes Tests Layout
23 24 16 6 12
A File Undo and Object 7 An A Template
Viewer Redo Persistence Interpreter Expander
17 8 11
A Virtual Binary Functions and An HTML
A Debugger
Machine Data Closures Validator
26 25
18 9 12
A Code 5 Parsing
A Database Protocols
Linter Text
Legend
15 10 3
4
Performance A File Finding
source
Profiling Archiver Duplicate Files Matching
Patterns
sink 21
22 Serving Transferring A Package 20
Web Pages Files Manager
These chapters (Figure 1.1) are also designed to help another persona:
Yim teaches two college courses on software development. They are frustrated that
so many books talk about details but not about design and use examples that their
students can’t relate to. This book will give them material they can use in class and
starting points for course projects.
A B A B
A B
C F C F
C
D E D E
expert
novice
Comprehension
Abstraction
curve means that for any given task, the code that is quickest for a novice to comprehend
will almost certainly be different from the code that an expert can understand most quickly.
Our third big idea is that programs are just another kind of data. Source code is just text,
which we can process like other text files. Likewise, a program in memory is just a data
structure that we can inspect and modify like any other. Treating code like data enables us
to solve hard problems in elegant ways, but at the cost of increasing the level of abstraction
in our programs. Once again, finding the balance is what we mean by “design”.
1.3 Formatting
We display Python source code like this:
for ch in "example ":
print(ch)
alpha
beta
gamma
delta
We use ... to show where lines have been omitted, and occasionally break lines in
unnatural ways to make them fit on the page. Where we do this, we end all but the last line
with a single backslash \. Finally, we show glossary entries in bold text and write functions
as function_name rather than function_name(). The latter is more common, but the empty
parentheses makes it hard to tell whether we’re talking about the function itself or a call to
the function with no parameters.
1.4 Usage
The source for this book is available in our Git repository4 and all of it can be read on our
website5 . All of the written material in this book is licensed under the Creative Commons -
Attribution - NonCommercial 4.0 International license6 (CC-BY-NC-4.0), while the software
is covered by the Hippocratic License7 . The first license allows you to use and remix this
material for noncommercial purposes, as-is or in adapted form, provided you cite its orig-
inal source; if you want to sell copies or make money from this material in any other way,
you must contact us8 and obtain permission first. The second license allows you to use
and remix the software on this site provided you do not violate international agreements
governing human rights; please see Appendix D for details.
If you would like to improve what we have, add new material, or ask questions, please
file an issue in our GitHub repository9 or send an email10 . All contributors are required to
abide by our Code of Conduct (Appendix E).
1.6 Acknowledgments
Like [Wilson2022a], this book was inspired by [Kamin1990; Kernighan1979; Kernighan1981;
Kernighan1983; Kernighan1988; Oram2007; Wirth1976] and by:
• The Architecture of Open Source Applications 15 series [Brown2011; Brown2012; Arm-
strong2013; Brown2016];
• Mary Rose Cook’s16 Gitlet17 ;
• Matt Brubeck’s18 browser engine tutorial19 ;
• Web Browser Engineering 20 by Pavel Panchekha21 and Chris Harrelson22 ;
• Connor Stack’s23 database tutorial24 ;
• Maël Nison’s25 package manager tutorial26 ;
• Paige Ruten’s27 kilo text editor28 and Wasim Lorgat’s29 editor tutorial30 ;
• Bob Nystrom’s31 Crafting Interpreters 32 [Nystrom2021]; and
• the posts and zines33 created by Julia Evans34 .
12 https://mastodon.social/@jenn@pixel.kitchen/109985276835264400
13 https://emilygorcenski.com/post/book-report-software-design-by-example-by-greg-wilson/
14 https://blog.djnavarro.net/posts/2023-05-31_software-design-by-example/
15 https://aosabook.org/
16 https://maryrosecook.com/
17 http://gitlet.maryrosecook.com/
18 https://limpet.net/mbrubeck/
19 https://limpet.net/mbrubeck/2014/08/08/toy-layout-engine-1.html
20 https://browser.engineering/
21 https://pavpanchekha.com/
22 https://twitter.com/chrishtr
23 https://connorstack.com/
24 https://cstack.github.io/db_tutorial/
25 https://arcanis.github.io/
26 https://classic.yarnpkg.com/blog/2017/07/11/lets-dev-a-package-manager/
27 https://viewsourcecode.org/
28 https://viewsourcecode.org/snaptoken/kilo/index.html
29 https://wasimlorgat.com/
30 https://github.com/seem/editor
31 http://journal.stuffwithstuff.com/
32 https://craftinginterpreters.com/
33 https://wizardzines.com/
34 https://jvns.ca/
6 1 Introduction
I am grateful to Miras Adilov, Alvee Akand, Rohan Alexander, Alexey Alexapolsky, Lina
Andrén, Alberto Bacchelli, Yanina Bellini Saibene, Matthew Bluteau, Adrienne Canino, Marc
Chéhab, Stephen Childs, Hector Correa, Socorro Dominguez, Christian Drumm, Christian
Epple, Julia Evans, Davide Fucci, Thomas Fritz, Francisco Gabriel, Florian Gaudin-Delrieu,
Craig Gross, Jonathan Guyer, McKenzie Hagen, Han Qi, Fraser Hay, Alexandru Hurjui,
Bahman Karimi, Carolyn Kim, Kitsios Konstantinos, Jenna Landy, Peter Lin, Zihan Liu,
Becca Love, Dan McCloy, Ramiro Mejia, Michael Miller, Firas Moosvi, Joe Nash, Sheena
Ng, Reiko Okamoto, Juanan Pereira, Mahmoodur Rahman, Arpan Sarkar, Silvan Schlegel,
Rosan Shanmuganathan, Dave W. Smith, Stephen M. Sturdevant, Diyar Taskiran, Ece Tur-
nator, and Yao Yundong for feedback on early drafts of this material.
I am also grateful to Shashi Kumar for help with LaTeX, to Odin Beuchat35 for help with
JavaScript, and to the creators of Black36 , flake837 , Glosario38 , GNU Make39 , isort40 , ark41 ,
LaTeX42 , pip43 , Python44 , Remark45 , WAVE46 , and many other open source tools: if we all
give a little, we all get a lot.
All royalties from this book will go to the Red Door Family Shelter47 in Toronto.
1.7 Exercises
Setting Up
1. Use pip48 to install Black49 , flake850 , and isort51 on your computer.
2. Run them on a few programs you have already written. (The file setup.cfg in the root
directory of this book’s GitHub repository52 has the settings we use for these tools.) What
problems do they report? Which of these reports do you disagree with?
Avoiding Potholes
Go to the GitHub repository53 for this book and look at the open issues. Which of them can
you understand? What makes the others hard to understand? What could you add, leave
out, or write differently when you report a problem that you have found?
35 https://www.drafolin.ch/
36 https://black.readthedocs.io/
37 https://flake8.pycqa.org/
38 https://glosario.carpentries.org/
39 https://www.gnu.org/software/make/
40 https://pycqa.github.io/isort/
41 https://www.dmulholl.com/docs/ark/main/
42 https://www.latex-project.org/
43 https://pip.pypa.io/
44 https://www.python.org/
45 https://remarkjs.com/
46 https://wave.webaim.org/
47 https://www.reddoorshelter.ca/
48 https://pip.pypa.io/
49 https://black.readthedocs.io/
50 https://flake8.pycqa.org/
51 https://pycqa.github.io/isort/
52 https://github.com/gvwilson/sdxpy/
53 https://github.com/gvwilson/sdxpy/
2
Objects and Classes
• Objects are useful without classes, but classes make them easier to understand.
• A well-designed class defines a contract that code using its instances can rely on.
• Objects that respect the same contract are polymorphic, i.e., they can be used
interchangeably even if they do different specific things.
• Inheritance can be implemented in several ways that differ in the order in which
objects and classes are searched for methods.
Terms defined: alias, argument, cache, class method, constructor, derived class,
design by contract, monkey patching, multiple inheritance, object-oriented
programming, parameter, polymorphism, recursion, spread, static method,
upcall, varargs
We are going to create a lot of objects and classes in these lessons, and they will be a
lot easier to use if we understand how they are implemented. Historically, object-oriented
programming (OOP) was invented to solve two problems:
2. How can we organize code to make it easier to understand, test, and extend?
2.1 Objects
As a motivating problem, let’s define some of the things a generic shape in a drawing
package must be able to do:
class Shape:
def __init__(self , name ):
self.name = name
def perimeter(self ):
raise NotImplementedError (" perimeter ")
def area(self ):
raise NotImplementedError (" area ")
A specification like this is sometimes called a contract because an object must satisfy it
in order to be considered a shape, i.e., must provide methods with these names that do
7
8 2 Objects and Classes
what those names suggest. For example, we can derive classes from Shape to represent
squares and circles.
class Square(Shape ):
def __init__(self , name , side ):
super (). __init__(name)
self.side = side
def perimeter(self ):
return 4 * self.side
def area(self ):
return self.side ** 2
class Circle(Shape ):
def __init__(self , name , radius ):
super (). __init__(name)
self.radius = radius
def perimeter(self ):
return 2 * math.pi * self.radius
def area(self ):
return math.pi * self.radius ** 2
Since squares and circles have the same methods, we can use them interchangeably.
This is called polymorphism, and it reduces cognitive load by allowing the people using
related things to ignore their differences:
examples = [Square ("sq", 3), Circle ("ci", 2)]
for thing in examples:
n = thing.name
p = thing.perimeter ()
a = thing.area ()
print(f"{n} has perimeter {p:.2f} and area {a:.2f}")
But how does polymorphism work? The first thing we need to understand is that a func-
tion is an object. While the bytes in a string represent characters and the bytes in an image
represent pixels, the bytes in a function are instructions (Figure 2.1). When Python exe-
cutes the code below, it creates an object in memory that contains the instructions to print
a string and assigns that object to the variable example:
def example ():
print ("in example ")
We can create an alias for the function by assigning it to another variable and then call the
function by referencing that second variable. Doing this doesn’t alter or erase the connection
between the function and the original name:
alias = example
alias ()
in example
We can also store function objects in data structures like lists and dictionaries. Let’s
write some functions that do the same things as the methods in our original Python and
store them in a dictionary to represent a square (Figure 2.2):
2.1 Objects 9
bytes
74 69 73 27 61 20 6C 6C 6A 20 73 75 20 74 79 62 65 74 0A 73
as text as instructions
as image old_x = x
"it's all just bytes"
x=2*x+1
Figure 2.1: Bytes can be interpreted as text, images, instructions, and more.
name "sq"
side 2
square
perim square_perim()
area square_area()
name "ci"
radius 3
circle
perim circle_perim()
area circle_area()
def square_perimeter(thing ):
return 4 * thing [" side "]
def square_area(thing ):
return thing [" side "] ** 2
If we want to use one of the “methods” in this dictionary, we call it like this:
def call(thing , method_name ):
return thing[method_name ]( thing)
The function call looks up the function stored in the dictionary, then calls that function with
the dictionary as its first object; in other words, instead of using obj.meth(arg) we use
obj["meth"](obj, arg). Behind the scenes, this is (almost) how objects actually work.
10 2 Objects and Classes
We can think of an object as a special kind of dictionary. A method is just a function that
takes an object of the right kind as its first parameter (typically called self in Python).
2.2 Classes
One problem with implementing objects as dictionaries is that it allows every single object
to behave slightly differently. In practice, we want objects to store different values (e.g.,
different squares to have different sizes) but the same behaviors (e.g., all squares should
have the same methods). We can implement this by storing the methods in a dictionary
called Square that corresponds to a class and having each individual square contain a ref-
erence to that higher-level dictionary (Figure 2.3). In the code below, that special reference
uses the key "_class":
def square_perimeter(thing ):
return 4 * thing [" side "]
def square_area(thing ):
return thing [" side "] ** 2
Square = {
"perimeter ": square_perimeter ,
"area ": square_area ,
"_classname ": "Square"
}
Calling a method now involves one more lookup because we have to go from the object
to the class to the method, but once again we call the “method” with the object as the first
argument:
Square
name "sq"
square side 2 _classname "square"
_class perim square_perim()
area square_area()
Circle
name "ci"
circle radius 3 _classname "circle"
_class perim circle_perim()
area circle_area()
As a bonus, we can now reliably identify objects’ classes and ask whether two objects are
of the same class or not by checking what their "_class" keys refer to.
2.3 Arguments
The methods we have defined so far operate on the values stored in the object’s dictionary,
but none of them take any extra arguments as input. Implementing this is a little bit tricky
because different methods might need different numbers of arguments. We could define
functions call_0, call_1, call_2 and so on to handle each case, but like most modern
languages, Python gives us a better way. If we define a parameter in a function with a
leading *, it captures any “extra” values passed to the function that don’t line up with named
parameters. Similarly, if we define a parameter with two leading stars **, it captures any
extra named parameters:
def show_args(title , *args , ** kwargs ):
print(f"{ title} args '{args}' and kwargs '{kwargs }'")
all_in_list = [1, 2, 3]
show_spread (* all_in_list)
all_in_dict = {" right ": 30, "left ": 10, "middle ": 20}
show_spread (** all_in_dict)
With these tools in hand, let’s add a method to our Square class to tell us whether a
square is larger than a user-specified size:
def square_larger(thing , size ):
return call(thing , "area ") > size
Square = {
"perimeter ": square_perimeter ,
"area ": square_area ,
"larger ": square_larger ,
"_classname ": "Square"
}
The function that implements this check for circles looks exactly the same:
def circle_larger(thing , size ):
return call(thing , "area ") > size
We then modify call to capture extra arguments in *args and spread them into the function
being called:
def call(thing , method_name , *args ):
return thing [" _class "][ method_name ](thing , *args)
is sq larger? False
is ci larger? True
However, we now have two functions that do exactly the same thing—the only difference
between them is their names. Anything in a program that is duplicated in several places
will eventually be wrong in at least one, so we need to find some way to share this code.
2.4 Inheritance
The tool we want is inheritance. To see how this works in Python, let’s add a method called
density to our original Shape class that uses other methods defined by the class
Random documents with unrelated
content Scribd suggests to you:
unaware. Round the two which contain water there are some rude
stone water troughs, which may be of any age.
These being the limits of the country, let us return again to a
consideration of its physical aspects.
The physical features of the country naturally depend upon its
geological formation. The ranges of hills, east and west of Jordan,
are formed almost entirely of beds of cretaceous limestone, which
were once continuous. The Jordan Valley coincides with a line of
fault; that is to say, the rocky strata cracked in an irregular line from
north to south, and the country west of this fault sank down bodily,
so that the higher strata of rocks on that side abut now against the
lower strata on the eastern side. With this depression to begin with,
the rains and torrents have gradually sculptured the valley into its
present form.
The maritime district of Palestine, stretching from the base of
Carmel southwards by Joppa and Gaza to the Desert of Beersheba,
consists of a series of low hills from 300 feet to 400 feet high,
separated by valleys and alluvial plains extending inland to a varying
distance. The coast line is bordered by a line of sand-hills, which,
when unrestrained by some physical barrier, are ever moving inland
with disastrous effect. The district is largely composed of beds of
sand and gravel, which have once been the bed of the outer sea;
while along the line of many of the rivers and streams a deposit of
rich loam of a deep brown colour covers considerable areas, and
yields abundant crops of wheat and maize to the cultivators.
Professor Edward Hull, the eminent geologist, who was
commissioned by the Palestine Exploration Society to investigate the
geology of the Desert and the Holy Land, reported the results to the
Committee, in an elaborate Memoir, in which he treats of the
maritime district, the table-land of Western Palestine and the Tih
Desert, the depression of the Jordan Valley and its continuation
southward to the Gulf of Akabah, the elevated plateau east of
Jordan, and the mountainous tract of the peninsula of Sinai. Utilising
the labours of his predecessors, Russeger, Fraas, Lartet, Vignes, &c.,
he sometimes confirms their results, and sometimes adds to our
knowledge.
GEOLOGICAL SKETCH MAP
of
SINAI & PALESTINE
(based chiefly upon the Maps of M.M. Lartet, Hull & Zittel.)
The figures represent deviations above the sea level in English feet; those with a
minus mark represent depressions below sea level.
It is pointed out by Sir George Grove that the name “Dead Sea”
never occurs in the Bible, and appears not to have existed until the
second century after Christ. It originated in an erroneous opinion,
and there can be little doubt that to the name are due in a great
measure the mistakes and misrepresentations which were for so
long prevalent regarding this lake, and which have not indeed yet
wholly ceased to exist. In the Old Testament it is called the Salt Sea,
and the Sea of the Plain (Arabah). By the Arabs it is called El Bahr
Lut (the Sea of Lot).
The Salt Sea lies in the deepest part of the great Jordan-Arabah
depression, and the ground rises to the south of it, as well as in all
other directions. It was shown, in fact, by Colonel Kitchener’s survey
of the Arabah that the bed of the valley, for the most part, is raised
above the level of the Gulf of Akabah. From the border of the Dead
Sea southward the ground rises but little for 10 miles, but then
begins to rise rapidly, so that at a distance of about 40 miles it is as
high as the sea level at Akabah; and 29 miles further south it is 660
feet above that level.
The Jordan Valley, as already stated, coincides with a great fault
in the strata. This had been recognised by Lartet, Tristram, Wilson,
and others; and Professor Hull has traced the continuation of this
fracture, at the base of the Edomite mountains along the Arabah
Valley. He agrees with Lartet in thinking that the waters of the
Jordan Valley have not flowed down into the Gulf of Akabah since
the land emerged from the ocean. The disconnection of the inner
waters from the outer is a very ancient event, dating back to
Miocene times.
The River Jordan, throughout its course, from the Sea of Tiberias
to the Salt Sea, cuts its channel through alluvial terraces, consisting
of sand, gravel, and calcareous marl, which sometimes contain
shells, semi-fossilised, but of species still living in the lakes of
Tiberias and Huleh. These terraces are continuous round the shores
of the Salt Sea, and between the base of the cliffs of Jebel Karantul,
near Jericho, and the fords of the Jordan, three of them may be
observed,
the first being at a level of 650 to 600 feet,
the second being at a level of 520 to 250 feet,
the third being at a level of 200 to 130 feet
and below the last named is the alluvial flat, liable to be flooded on
the rise of the waters. The upper surfaces and outer margins of
these terraces indicate successive stages, at which the waters have
rested in sinking down to their present level. Originally they reached
a level somewhat over that of the Mediterranean, and at that time a
great inland lake extended from Lake Huleh southwards into the
Arabah Valley, its length being about 200 miles.
In the Jordan Valley, the upper terrace, at the foot of the hills, is
called the Ghor, and it is to be distinguished from the Zor, or bottom
of the valley, in which the channel of the river, cut still deeper,
meanders.
The Salt Sea itself is enclosed on all sides by terraced hills, except
towards the north, where it receives the waters of the Jordan. In
rising gradually out of the ocean, the region appears to have rested
several times at successive levels, and the sea left its mark in
deposits of marl, gravel, and silt. Beyond the southern end of the
Salt Sea the banks of the Ghor rise in the form of a great white
sloping wall, to a height of about 600 feet above the plain, and are
formed of horizontal courses of sand and gravel, resting on white
marl and loam. This mural wall sweeps round in a semicircular form
from side to side of the Ghor. The upper surface is nearly level
(except where broken into by river channels), and from its base
stretches a plain covered partly, over the western side, by a forest of
small trees and shrubs, and partly by vegetation affording pasturage
to the numerous flocks of the Arabs, who settle down here during
the cooler months of the year. It is impossible to doubt that at no
remote period the waters of the Salt Sea, though now distant some
10 miles, washed the base of these cliffs, and a rise of a few feet
would submerge this verdant plain, and bring back the sea to its
former more extended limits.
From this position also, the white terrace of Jebel Usdum—“the
salt mountain” where the Crusaders wrongly placed Sodom—is seen
projecting from the sides of the loftier limestone terraces of the
Judæan hills. Towards the east, similar terraces of whitish alluvial
deposits are seen clinging to the sides of the Moabite hills, or
running far up the deep glens which penetrate the sides of the great
table-land. In these terraces, the upper surfaces of which reach a
level of about 600 feet above the waters of the Salt Sea, we behold
but the remnants of an ancient sea-bed, which must originally have
stretched from side to side.
Eight hundred feet higher than these terraces there are others
composed of marl, gravel, and silt, through which the ravines of
existing streams have been cut; and this indicates that the level of
the Salt Sea stood at one time 100 feet higher than the waters of
the Mediterranean stand now.
Origin of the saltness of the Dead Sea.—It has been generally
recognised that the waters of lakes which have no outlet ultimately
become more or less saline. Of these the most important in the old
world are the Caspian, the Sea of Aral, Lakes Balkash, Van, Urumiah,
and, lastly, the Dead Sea, or as it was originally called, “the Salt
Sea.” “The Caspian,” says Professor Hull, “owing to its great extent
and other causes, is but slightly saline; but that with which we have
here to deal is the most saline of all. It is probable that the water of
the ocean itself has become salt owing to the same cause which has
produced saltness in the inland lakes, as it may be regarded as a
mass of water without an outlet. The cause of the saltness in such
lakes I now proceed to explain.
“It has been found that the waters of rivers contain, besides
matter which is in a state of mechanical suspension, carbonates of
lime and magnesia, and saline ingredients in a state of solution; and
as those lakes which have an outlet, such as the Sea of Galilee, part
with their waters and saline ingredients as fast as they receive them,
the waters of such lakes remain fresh. It is otherwise, however, with
regard to lakes which have no outlet. In such cases the water is
evaporated as fast as it is received; and as the vapour is in a
condition of purity, the saline ingredients remain behind. Thus the
waters of such a lake tend constantly to increase in saltness, until a
state of saturation is attained, when the excess of salt is
precipitated, and forms beds at the bottom of the lake. The contrast
presented by the waters of the Sea of Galilee on the one hand, and
those of the Dead Sea on the other, though both are fed by the
same river, is a striking illustration of the effects resulting from
opposite physical conditions. In the former case, the waters are
fresh, and abound in fishes and molluscs; in the latter, they are so
intensely salt that all animal life is absent.
“The increase of saltness in the waters of the Dead Sea has
probably been very slow, and dates back from its earliest condition,
when its waters stretched for a distance of about 200 miles from
north to south....
“The excessive salinity of the waters of the Dead Sea will be
recognised from a comparison with those of the Atlantic Ocean.
Thus, while the waters of the ocean give six pounds of salt, &c., in a
hundred pounds of water, those of the Dead Sea give 24·57 pounds
in the same quantity; but in both cases the degree of salinity varies
with the depth, the waters at the surface being less saline than
those near the bottom....
“As to the depth of the waters:—The floor of the Dead Sea has
been sounded on two occasions: first, by the Expedition under
Lieutenant Lynch in 1848, and secondly, by that under the Duc de
Luynes. In the former case the maximum depth was found to be
1278 feet; in the latter 1217 feet, being close approximations to
each other. We may therefore affirm that the floor of the lake
descends to nearly as great a depth below its surface as the surface
itself below the level of the Mediterranean Sea.
“The section given by Lynch indicates that the place of greatest
depth lies much nearer the Moabite than the Judæan shore, and the
descent from the base of the Moabite escarpment below Jebel
Attarus and between the outlets of the Wâdies Mojeb and Zerka
Maïn, is very steep indeed. The deepest part of the trough seems to
lie in a direction running north and south, at a distance of about 2
miles from the eastern bank; and while the ascent towards this bank
is rapid, that towards the Judæan shore on the west is comparatively
gentle. The line of this deep trough seems exactly to coincide with
that of the great Jordan Valley fault. From the bottom of the deeper
part, the sounding line brought up specimens of crystals of salt
(sodium-chloride), and it can scarcely be doubted that a bed of this
mineral, together with gypsum, is in course of formation over the
central portions of the Dead Sea.”
[Authorities and Sources:—“Memoirs of the Survey: Geology”, Dr E. Hull.
Smith’s “Dict. of Bible.” “Tent Work in Palestine.” By Major Conder, R.E.]
5. “Lot’s Wife.”
In connection with the destruction of Sodom, the Bible mentions
the fate which overtook Lot’s wife, who “became a pillar of salt.” In
the Book of Wisdom also we read of the waste land that smoketh,
and plants bearing fruit that never come to ripeness, and a standing
pillar of salt—a monument of an unbelieving soul (Wisd. x. 7).
Josephus also says that he had seen it (Ant. i. 11, 4). The Arabs
have legends on the subject; and travellers now and again describe
the pillars of salt which have been pointed out to them, and to which
the legends attach. The stories are by no means modern. Major
Conder, in his “Syrian Stone Lore,” brings into brief compass the
notions of the Fathers of the Church on the subject. From an early
period “Lot’s wife” is mentioned as standing by the western shores
of the Dead Sea, and Antoninus Martyr is careful to combat the idea
that the pillar of salt was destroyed through its being constantly
licked by animals. Clemens Romanus had seen it; Irenæus also (IV.
xxxi. 3) mentions “Lot’s wife” as a pillar still standing. (Quoted by
Kitto, Cyclopæd. “Lot.”) So does Benjamin of Tudela, whose account
is more than usually circumstantial; and in later times Maundrell and
others. It seems possibly to be the natural pinnacle, now called
Karnet Sahsul Hameid, to which these writers refer. The feminine
nature of this statue was supposed to be still perceptible, in spite of
petrification.
Perhaps the best account of “Lot’s wife” is to be found in E. H.
Palmer’s “Desert of the Exodus,” where a coloured plate helps the
realisation.
“While with the Ghawárineh” (says Palmer) “we had heard
strange rumours that ‘a statue’ called ‘Lot’s wife’ existed on the
eastern shore of the Dead Sea, but none of them had ever seen it,
or could give us a satisfactory description of it. Making cautious
inquiries amongst the Beni Hamideh, we found that the statement
was correct, and after some little trouble, guides were procured who
offered to conduct us to the spot.... Our path led us to another
plateau, about 1000 feet above the Dead Sea, and on the extreme
edge of this was the object of which we were in search—Bint Sheikh
Lot, or ‘Lot’s wife.’ It is a tall isolated needle of rock, which does
really bear a curious resemblance to an Arab woman with a child
upon her shoulder. The Arab legend of Lot’s wife differs from the
Bible account only in the addition of a few frivolous details. They say
that there were seven Cities of the Plain, and that they were all
miraculously overwhelmed by the Dead Sea as a punishment for
their crimes. The prophet Lot and his family alone escaped the
general destruction; he was divinely warned to take all that he had
and flee eastward, a strict injunction being given that they should
not look behind them. Lot’s wife, who had on previous occasions
ridiculed her husband’s prophetic office, disobeyed the command,
and, turning to gaze upon the scene of the disaster, was changed
into this pillar of rock.
“Travellers in all ages have discovered ‘Lot’s wife’ in the pillars
which atmospheric influences are constantly detaching from the
great masses of mineral salt at the southern end of the Dead Sea,
but these are all accidental and transient. The rock discovered by us
does not fulfil the requirements of the Scriptural story, but there can
be no doubt that it is the object which has served to keep alive for
so many ages the local tradition of the event.
“The sun was just setting as we reached the spot; and the
reddening orb sank down behind the western hills, throwing a bridge
of sheeny light across the calm surface of the mysterious lake. As we
gazed on the strange statue-like outline of the rock—at first brought
out into strong relief against the soft yet glowing hues of the
surrounding landscape, and then mingled with the deepening
shadows, and lost amid the general gloom as night came quickly on,
we yielded insensibly to the influence of the wild Arab tale, and
could almost believe that we had seen the form of the prophet’s wife
peering sadly after her perished home in the unknown depths of that
accursed sea.”
The Wars.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com