0% found this document useful (0 votes)
14 views

73159

The document provides a list of Python programming ebooks available for instant download at ebookgate.com, including titles like 'Advanced Computer Programming in Python' and 'Practical Programming: An Introduction to Computer Science using Python.' It features various formats such as PDF, ePub, and MOBI, and includes detailed contents covering topics like Object Oriented Programming, Data Structures, and more. Users can access these resources with a single click to enhance their programming skills.

Uploaded by

sasayabuscar37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

73159

The document provides a list of Python programming ebooks available for instant download at ebookgate.com, including titles like 'Advanced Computer Programming in Python' and 'Practical Programming: An Introduction to Computer Science using Python.' It features various formats such as PDF, ePub, and MOBI, and includes detailed contents covering topics like Object Oriented Programming, Data Structures, and more. Users can access these resources with a single click to enhance their programming skills.

Uploaded by

sasayabuscar37
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Instant Ebook Access, One Click Away – Begin at ebookgate.

com

Advanced Computer Programming in Python 1st


Edition Karim Pichara

https://ebookgate.com/product/advanced-computer-programming-
in-python-1st-edition-karim-pichara/

OR CLICK BUTTON

DOWLOAD EBOOK

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


Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Practical programming An introduction to computer science


using Python Jennifer Campbell

https://ebookgate.com/product/practical-programming-an-introduction-
to-computer-science-using-python-jennifer-campbell/

ebookgate.com

OpenCV with Python blueprints design and develop advanced


computer vision projects using OpenCV with Python 1st
Edition Michael Beyeler
https://ebookgate.com/product/opencv-with-python-blueprints-design-
and-develop-advanced-computer-vision-projects-using-opencv-with-
python-1st-edition-michael-beyeler/
ebookgate.com

Ultimate Python Programming 1st Edition Deepali Srivastava

https://ebookgate.com/product/ultimate-python-programming-1st-edition-
deepali-srivastava/

ebookgate.com

Expert Python Programming 2nd Edition Jaworski

https://ebookgate.com/product/expert-python-programming-2nd-edition-
jaworski/

ebookgate.com
Python Programming 4th Edition Singh A.

https://ebookgate.com/product/python-programming-4th-edition-singh-a/

ebookgate.com

Black hat Python Python programming for hackers and


pentesters 1st Edition Seitz

https://ebookgate.com/product/black-hat-python-python-programming-for-
hackers-and-pentesters-1st-edition-seitz/

ebookgate.com

OpenCV Computer Vision with Python 1st Edition Howse

https://ebookgate.com/product/opencv-computer-vision-with-python-1st-
edition-howse/

ebookgate.com

Computer Programming 1st Edition E. Balagurusamy

https://ebookgate.com/product/computer-programming-1st-edition-e-
balagurusamy/

ebookgate.com

Practical Maya Programming with Python 1st Edition


Galanakis

https://ebookgate.com/product/practical-maya-programming-with-
python-1st-edition-galanakis/

ebookgate.com
Contents

Contents 5

1 Object Oriented Programming 9


1.1 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.2 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3 Aggregation and Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5 Multiple Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.6 Abstract Base Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.7 Class Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.8 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

2 Data Structures 45
2.1 Array-Based Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.2 Node-based Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
2.3 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

3 Functional Programming 101


3.1 Python Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
3.2 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
3.3 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130

4 Meta Classes 135


4.1 Creating classes dynamically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
4.2 Metaclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
4.3 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
6 CONTENTS

5 Exceptions 147
5.1 Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.2 Raising exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
5.3 Exception handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
5.4 Creating customized exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
5.5 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

6 Testing 163
6.1 Unittest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
6.2 Pytest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
6.3 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

7 Threading 185
7.1 Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
7.2 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
7.3 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

8 Simulation 209
8.1 Synchronous Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
8.2 Discrete Event Simulation (DES) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
8.3 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222

9 Handling Strings and Bytes 227


9.1 Some Built-in Methods for Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
9.2 Bytes and I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
9.3 bytearrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
9.4 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240

10 I/O Files 245


10.1 Context Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
10.2 Emulating files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

11 Serialization 253
11.1 Serializing web objects with JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
11.2 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
CONTENTS 7

12 Networking 263
12.1 How to identify machines on internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.2 Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.3 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
12.4 Client-Server Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
12.5 Sending JSON data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
12.6 Sending data with pickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
12.7 Hands-On Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

13 Web Services 277


13.1 HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
13.2 REST architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
13.3 Client-side Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
13.4 Server-side Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
13.5 Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
13.6 Request Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
13.7 Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
13.8 Other architectures for Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289

14 Graphical User Interfaces 291


14.1 PyQt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
14.2 Layouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
14.3 Events and Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
14.4 Sender . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
14.5 Creating Custom Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
14.6 Mouse and Keyboard Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
14.7 QT Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308

15 Solutions for Hands-On Activities 315


15.1 Solution for activity 1.1: Variable stars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
15.2 Solution for activity 1.2: Geometric Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
15.3 Solution for activity 2.1: Production line of bottles . . . . . . . . . . . . . . . . . . . . . . . . 326
15.4 Solution for activity 2.2: Subway Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
15.5 Solution for activity 3.1: Patients in a Hospital . . . . . . . . . . . . . . . . . . . . . . . . . . 332
8 CONTENTS

15.6 Solution for activity 3.2: Soccer Team . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334


15.7 Solution for activity 3.3: Hamburger Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
15.8 Solution for activity 4.1: MetaRobot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
15.9 Solution for activity 5.1: Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
15.10 Solution for activity 6.1: Testing the encryptor . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
15.11 Solution for activity 6.2: Testing ATMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
15.12 Solution for activity 7.1: Godzilla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
15.13 Solution for activity 7.2: Mega Godzilla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
15.14 Solution for activity 8.1: Client queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
15.15 Solution for activity 8.2: GoodZoo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
15.16 Solution for activity 9.1: Fixing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
15.17 Solution for activity 9.2: Audio files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
15.18 Solution for activity 11.1: Cashiers’ data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383

Bibliography 389
KARIM PICHARA – CHRISTIAN PIERINGER

ADVANCED COMPUTER PROGRAMMING IN PYTHON


ADVANCED COMPUTER PROGRAMMING IN PYTHON

Copyright © 2017 by Karim Pichara and Christian Pieringer


All rights reserved. This book or any portion thereof may not be reproduced or used in
any manner whatsoever without the express written permission of the publisher except
for the use of brief quotations in a book review.

ISBN: 9781521232385
To our wives and children
Preface

This book contains most of the relevant topics necessary to be an advanced computer programmer. The language used
in the book is Python 3. Besides the programming language, the reader will learn most of the backbone contents in
computer programming, such as object-oriented modeling, data structures, functional programming, input/output,
simulation, graphical interfaces, and much more. We believe that the best way to learn computer programming is to
work in hands-on activities. Practical exercises make the user get familiar with the main challenges that programming
brings, such as how to model a particular problem; or how to write good code and efficient routine implementation,
among others. Most of the chapters contain a set of hands-on activities (with proposed solutions) at the end. We
encourage the readers to solve all those assignments without previously checking the solution. Challenges may be hard
for initial programmers, but while going through this book, the activities will become more achievable for the reader.
This book contains most of the material used for the Advanced Python Programming course taught at PUC University
in Chile, by professors Karim Pichara and Christian Pieringer. The course is intended for Computer Science students
as well as any other affine career that can be benefited by computer programming knowledge. Of course, this book
is not enough to become a Software Engineer; there are other necessary courses that the reader must take to learn
more advanced concepts related to the development of bigger software projects. Some of the recommended courses
are Database Systems, Data Structures, Operating Systems, Compilers, Software Engineering, Testing, Software
Architecture, and Software Design, among others. The content of this book will prepare the reader to have the necessary
background for any of the next Software Engineering courses listed above. While using this book, readers should
follow along on their computers to be able to try all the examples included in the chapters. It will be necessary that
computers have already installed the required Python libraries.
3

Authors

Karim Pichara Baksai


Ph.D. in Computer Science,
Research Area: Machine Learning and Data Science applied to Astron-
omy
Associate Professor, Computer Science Department
Pontificia Universidad Católica de Chile (PUC)

Christian Pieringer Baeza


Ph.D. in Computer Science
Research Area: Computer Vision and Machine Learning
Adjunt Professor, Computer Science Department
Pontificia Universidad Católica de Chile (PUC)
4

Acknowledgments

This book was not possible without the constant help of the teaching assistants; they gave us invaluable feedback,
code and text editions to improve the book. The main collaborators who highly contributed are Belén Saldías, Ivania
Donoso, Marco Bucchi, Patricio López, and Ignacio Becker.

We would like also thank the team of assistants who worked in the hands-on activities: Jaime Castro, Rodrigo Gómez,
Bastián Mavrakis, Vicente Dominguez, Felipe Garrido, Javiera Astudillo, Antonio Gil, and José María De La Torre.

Belén Saldías Ivania Donoso Marco Bucci

Patricio López Ignacio Becker


Chapter 1

Object Oriented Programming

In the real world, objects are tangible; we can touch and feel them, they represent something meaningful for us. In the
software engineering field, objects are a virtual representation of entities that have a meaning within a particular context.
In this sense, objects keep information/data related to what they represent and can perform actions/behaviors using
their data. Object Oriented Programming (OOP) means that programs model functionalities through the interaction
among objects using their data and behavior. The way OOP represents objects is an abstraction. It consists in to create
a simplified model of the reality taking the more related elements according to the problem context and transforming
them into attributes and behaviors. Assigning attributes and methods to objects involves two main concepts close
related with the abstraction: encapsulation and interface.

Encapsulation refers to the idea of some attributes do not need to be visualized by other objects, so we can produce
a cleaner code if we keep those attributes inside their respective object. For example, imagine we have the object
Amplifer that includes attributes tubes and power transformer. These attributes only make sense inside
the amplifier because other objects such as the Guitar do not need to interact with them nor visualize them. Hence,
we should keep it inside the object Amplifier.

Interface let every object has a “facade” to protect its implementation (internal attributes and methods) and interact
with the rest of objects. For example, an amplifier may be a very complex object with a bunch of electronic pieces
inside. Think of another object such as the Guitar player and the Guitar that only interact with the amplifier
through the input plug and knobs. Furthermore, two or more objects may have the same interface allowing us to
replace them independently of their implementation and without change how we use them. Imagine a guitar player
wants to try a tube amplifier and a solid state amp. In both cases, amplifiers have the interface (knobs an input plug)
and offer the same user experience independently of their construction. In that sense, each object can provide the
10 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

suitable interface according to the context.

1.1 Classes

From the OOP perspective, classes describe objects, and each object is an instance of a class. The class statement
allow us to define a class. For convention, we name classes using CamelCase and methods using snake_case.
Here is an example of a class in Python:

1 # create_apartment.py
2

4 class Apartment:
5 '''
6 Class that represents an apartment for sale
7 value is in USD
8 '''
9

10 def __init__(self, _id, mts2, value):


11 self._id = _id
12 self.mts2 = mts2
13 self.value = value
14 self.sold = False
15

16 def sell(self):
17 if not self.sold:
18 self.sold = True
19 else:
20 print("Apartment {} was sold"
21 .format(self._id))

To create an object, we must create an instance of a class, for example, to create an apartment for sale we have to call
the class Apartment with the necessary parameters to initialize it:

1 # instance_apartment.py
2

3 from create_apartment import Apartment


1.1. CLASSES 11

5 d1 = Apartment(_id=1, mts2=100, value=5000)


6

7 print("sold?", d1.sold)
8 d1.sell()
9 print("sold?", d1.sold)
10 d1.sell()

sold? False
sold? True
Apartment 1 was sold

We can see that the __init__ method initializes the instance by setting the attributes (or data) to the initial values,
passed as arguments. The first argument in the __init__ method is self, which corresponds to the instance itself.
Why do we need to receive the same instance as an argument? Because the __init__ method is in charge of the
initialization of the instance, hence it naturally needs access to it. For the same reason, every method defined in the
class that specifies an action performed by the instance must receive self as the first argument. We may think of
these methods as methods that belong to each instance. We can also define methods (inside a class) that are intended
to perform actions within the class attributes, not to the instance attributes. Those methods belong to the class and do
not need to receive self as an argument. We show some examples later.

Python provides us with the help(<class>) function to watch a description of a class:

1 help(Apartment)

#output

Help on class Apartment in module create_apartment:

class Apartment(builtins.object)
| Class that represents an apartment for sale
| price is in USD
|
| Methods defined here:
|
| __init__(self, _id, sqm, price)
12 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

|
| sell(self)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)

1.2 Properties

Encapsulation suggests some attributes and methods are private according to the object implementation, i.e., they
only exist within an object. Unlike other programming languages such as C++ or Java, in Python, the private concept
does not exist. Therefore all attributes/methods are public, and any object can access them even if an interface exist.
As a convention, we can suggest that an attribute or method to be private adding an underscore at the beginning
of its name. For example, _<attribute/method name>. Even with this convention, we may access directly
to the attributes or methods. We can strongly suggest that an element within an object is private using a double
underscore __<attribute/method name>. The name of this approach is name mangling. It concerns to the
fact of encoding addition semantic information into variables. Remember both approaches are conventions and good
programming practices.

Properties are the pythonic mechanism to implement encapsulation and the interface to interact with private attributes
of an object. It means every time we need that an attribute has a behavior we define it as property. In other way, we are
forced to use a set of methods that allow us to change and retrieve the attribute values, e.g, the commonly used pattern
get_value() and set_value(). This approach could generate us several maintenance problems.

The property() function allow us to create a property, receiving as arguments the functions use to get, set and delete
the attribute as property(<setter_function>, <getter_function>, <deleter_function>).
The next example shows the way to create a property:

1 # property.py
2

3 class Email:
1.2. PROPERTIES 13

5 def __init__(self, address):


6 self._email = address # A private attribute
7

8 def _set_email(self, value):


9 if '@' not in value:
10 print("This is not an email address.")
11 else:
12 self._email = value
13

14 def _get_email(self):
15 return self._email
16

17 def _del_email(self):
18 print("Erase this email attribute!!")
19 del self._email
20

21 # The interface provides the public attribute email


22 email = property(_get_email, _set_email, _del_email,
23 'This property contains the email.')

Check out how the property works once we create an instance of the Email class:

1 m1 = Email("[email protected]")
2 print(m1.email)
3 m1.email = "[email protected]"
4 print(m1.email)
5 m1.email = "kp2.com"
6 del m1.email

[email protected]
[email protected]
This is not an email address.
Erase this email attribute!!

Note that properties makes the assignment of internal attributes easier to write and read. Python also let us to define
properties using decorators. Decorators is an approach to change the behavior of a method. The way to create a
14 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

property through decorators is adding @property statement before the method we want to define as attribute. We
explain decorators in Chapter 3.

1 # property_without_decorator.py
2

3 class Color:
4

5 def __init__(self, rgb_code, name):


6 self.rgb_code = rgb_code
7 self._name = name
8

9 def set_name(self, name):


10 self._name = name
11

12 def get_name(self):
13 return self._name
14

15 name = property(get_name, set_name)

1 # property_with_decorator.py
2

3 class Color:
4

5 def __init__(self, rgb_code, name):


6 self._rgb_code = rgb_code
7 self._name = name
8

9 # Create the property using the name of the attribute. Then we


10 # define how to get/set/delet it.
11 @property
12 def name(self):
13 print("Function to get the name color")
14 return self._name
15

16 @name.setter
17 def name(self, new_name):
1.3. AGGREGATION AND COMPOSITION 15

18 print("Function to set the name as {}".format(new_name))


19 self._name = new_name
20

21 @name.deleter
22 def name(self):
23 print("Erase the name!!")
24 del self._name

1.3 Aggregation and Composition

In OOP there are different ways from which objects interact. Some objects are a composition of other objects who
only exists for that purpose. For instance, the object printed circuit board only exists inside a amplifier
and its existence only last while the amplifier exists. That kind of relationship is called composition. Another kind
of relationship between objects is aggregation, where a set of objects compose another object, but they may continue
existing even if the composed object no longer exist. For example, students and a teacher compose a classroom, but
both are not meant to be just part of that classroom, they may continue existing and interacting with other objects
even if that particular classroom disappears. In general, aggregation and composition concepts are different from the
modeling perspective. The use of them depends on the context and the problem abstraction. In Python, we can see
aggregation when the composed object receive instances of the components as arguments, while in composition, the
composed object instantiates the components at its initialization stage.

1.4 Inheritance

The inheritance concept allows us to model relationships like “object B is an object A but specialized in certain
functions”. We can see a subclass as a specialization of its superclass. For example, lets say we have a class called
Car which has attributes: brand, model and year; and methods: stop, charge_gas and fill_tires.
Assume that someone asks us to model a taxi, which is a car but has some additional specifications. Since we already
have defined the Car class, it makes sense somehow to re-use its attributes and methods to create a new Taxi class
(subclass). Of course, we have to add some specific attributes and methods to Taxi, like taximeter, fares or
create_receipt. However, if we do not take advantage of the Car superclass by inheriting from it, we will have
to repeat a lot of code. It makes our software much harder to maintain.

Besides inheriting attributes and methods from a superclass, inheritance allows us to “re-write” superclass methods.
Suppose that the subclass Motorcycle inherits from the class Vehicle. The method called fill_tires from
16 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

Vehicle has to be changed inside Motorcycle, because motorcycles (in general) have two wheels instead of four.
In Python, to modify a method in the subclass we just need to write it again, this is called overriding, so that Python
understands that every time the last version of the method is the one that holds for the rest of the code.

A very useful application of inheritance is to create subclasses that inherit from some of the Python built-in classes, to
extend them into a more specialized class. For example, if we want to create a custom class similar to the built-in class
list, we just must create a subclass that inherits from list and write the new methods we want to add:

1 # grocery_list.py
2

4 class GroceryList(list):
5

6 def discard(self, price):


7 for product in self:
8 if product.price > price:
9 # remove method is implemented in the class "list"
10 self.remove(product)
11 return self
12

13 def __str__(self):
14 out = "Grocery List:\n\n"
15 for p in self:
16 out += "name: " + p.name + " - price: "
17 + str(p.price) + "\n"
18

19 return out
20

21

22 class Product:
23

24 def __init__(self, name, price):


25 self.name = name
26 self.price = price
27

28
1.5. MULTIPLE INHERITANCE 17

29 grocery_list = GroceryList()
30

31 # extend method also belongs to 'list' class


32 grocery_list.extend([Product("bread", 5),
33 Product("milk", 10), Product("rice", 12)])
34

35 print(grocery_list)
36 grocery_list.discard(11)
37 print(grocery_list)

Grocery List:

name: bread - price: 5


name: milk - price: 10
name: rice - price: 12

Grocery List:

name: bread - price: 5


name: milk - price: 10

Note that the __str__ method makes the class instance able to be printed out, in other words, if we call
print(grocery_list) it will print out the string returned by the __str__ method.

1.5 Multiple Inheritance

We can inherit from more than one class. For example, a professor might be a teacher and a researcher, so she/he
should inherit attributes and methods from both classes:

1 # multiple_inheritance.py
2

4 class Researcher:
5

6 def __init__(self, field):


7 self.field = field
18 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

9 def __str__(self):
10 return "Research field: " + self.field + "\n"
11

12

13 class Teacher:
14

15 def __init__(self, courses_list):


16 self.courses_list = courses_list
17

18 def __str__(self):
19 out = "Courses: "
20 for c in self.courses_list:
21 out += c + ", "
22 # the [:-2] selects all the elements
23 # but the last two
24 return out[:-2] + "\n"
25

26

27 class Professor(Teacher, Researcher):


28

29 def __init__(self, name, field, courses_list):


30 # This is not completetly right
31 # Soon we will see why
32 Researcher.__init__(self, field)
33 Teacher.__init__(self, courses_list)
34 self.name = name
35

36 def __str__(self):
37 out = Researcher.__str__(self)
38 out += Teacher.__str__(self)
39 out += "Name: " + self.name + "\n"
40 return out
41

42
1.5. MULTIPLE INHERITANCE 19

43 p = Professor("Steve Iams",
44 "Meachine Learning",
45 [
46 "Python Programming",
47 "Probabilistic Graphical Models",
48 "Bayesian Inference"
49 ])
50

51 print(p)

#output

Research field: Meachine Learning


Courses: Python Programming, Probabilistic Graphical Models,
Bayesian Inference
Name: Steve Iams

Multiple Inheritance Problems

In Python, every class inherits from the Object class, that means, among other things, that every time we in-
stantiate a class, we are indirectly creating an instance of Object. Assume we have a class that inherits from
several superclasses. If we call to all the __init__ superclass methods, as we did in the previous example
(calling Researcher.__init__ and Teacher.__init__), we are calling the Object initializer twice:
Researcher.__init__ calls the initialization of Object and Teacher.__init__ calls the initialization of
Object as well. Initializing objects twice is not recommended. It is a waste of resources, especially in cases where
the initialization is expensive. It could be even worst. Imagine that the second initialization changes the setup done by
the first one, and probably the objects will not notice it. This situation is known as The Diamond Problem.

The following example (taken from [6]) shows what happens in the context of multiple-inheritance if each subclass
calls directly to initialize all its superclasses. Figure 1.1 indicates the hierarchy of the classes involved.

The example below (taken from [6]) shows what happens when we call the call() method in both superclasses from
SubClassA.

1 # diamond_problem.py
2
20 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

Figure 1.1: The diamond problem

3 class ClassB:
4 num_calls_B = 0
5

6 def make_a_call(self):
7 print("Calling method in ClassB")
8 self.num_calls_B += 1
9

10

11 class LeftSubClass(ClassB):
12 num_left_calls = 0
13

14 def make_a_call(self):
15 ClassB.make_a_call(self)
16 print("Calling method in LeftSubClass")
17 self.num_left_calls += 1
18

19

20 class RightSubClass(ClassB):
21 num_right_calls = 0
1.5. MULTIPLE INHERITANCE 21

22

23 def make_a_call(self):
24 ClassB.make_a_call(self)
25 print("Calling method in RightSubClass")
26 self.num_right_calls += 1
27

28

29 class SubClassA(LeftSubClass, RightSubClass):


30 num_calls_subA = 0
31

32 def make_a_call(self):
33 LeftSubClass.make_a_call(self)
34 RightSubClass.make_a_call(self)
35 print("Calling method in SubClassA")
36 self.num_calls_subA += 1
37

38

39 if __name__ == '__main__':
40 s = SubClassA()
41 s.make_a_call()
42 print("SubClassA: {}".format(s.num_calls_subA))
43 print("LeftSubClass: {}".format(s.num_left_calls))
44 print("RightSubClass: {}".format(s.num_right_calls))
45 print("ClassB: {}".format(s.num_calls_B))

Calling method in ClassB


Calling method in LeftSubClass
Calling method in ClassB
Calling method in RightSubClass
Calling method in SubClassA
SubClassA: 1
LeftSubClass: 1
RightSubClass: 1
ClassB: 2

From the output, we can see that the upper class in the hierarchy (ClassB) is called twice, despite that we just directly
22 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

call it once in the code.

Every time that one class inherits from two classes, a diamond structure is created. We refer the readers to
https://www.python.org/doc/newstyle/ for more details about new style classes. Following the same example shown
above, if instead of calling the make_a_call() method we call the __init__ method, we would be initializing
Object twice.

Solution to the diamond problem

One possible solution to the diamond problem is that each class must call the initialization of the superclass that
precedes it in the multiple inheritance resolution order. In Python, the order goes from left to right on the list of
superclasses from where the subclass inherits.

In this case, we just should call to super(), because Python will make sure to call the parent class in the multiple in-
heritance resolution order. In the previous example, after the subclass goes LeftSubclass, then RightSubClass,
and finally ClassB. From the following output, we can see that each class was initialized once:

1 # diamond_problem_solution.py
2

3 class ClassB:
4 num_calls_B = 0
5

6 def make_a_call(self):
7 print("Calling method in ClassB")
8 self.num_calls_B += 1
9

10

11 class LeftSubClass(ClassB):
12 num_left_calls = 0
13

14 def make_a_call(self):
15 super().make_a_call()
16 print("Calling method in LeftSubClass")
17 self.num_left_calls += 1
18

19
1.5. MULTIPLE INHERITANCE 23

20 class RightSubClass(ClassB):
21 num_right_calls = 0
22

23 def make_a_call(self):
24 super().make_a_call()
25 print("Calling method in RightSubClass")
26 self.num_right_calls += 1
27

28

29 class SubClassA(LeftSubClass, RightSubClass):


30 num_calls_subA = 0
31

32 def make_a_call(self):
33 super().make_a_call()
34 print("Calling method in SubClassA")
35 self.num_calls_subA += 1
36

37 if __name__ == '__main__':
38

39 s = SubClassA()
40 s.make_a_call()
41 print("SubClassA: {}".format(s.num_calls_subA))
42 print("LeftSubClass: {}".format(s.num_left_calls))
43 print("RightSubClass: {}".format(s.num_right_calls))
44 print("ClassB: {}".format(s.num_calls_B))

Calling method in ClassB


Calling method in RightSubClass
Calling method in LeftSubClass
Calling method in SubClassA
SubClassA: 1
LeftSubClass: 1
RightSubClass: 1
ClassB: 1
24 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

Method Resolution Order

The mro method shows us the hierarchy order. It is very useful in more complex multiple-inheritance cases. Python
uses the C3 [3] algorithm to calculate a linear order among the classes involved in multiple inheritance schemes.

1 # mro.py
2

3 from diamond_problem_solution import SubClassA


4

5 for c in SubClassA.__mro__:
6 print(c)

<class ’diamond_problem_solution.SubClassA’>
<class ’diamond_problem_solution.LeftSubClass’>
<class ’diamond_problem_solution.RightSubClass’>
<class ’diamond_problem_solution.ClassB’>
<class ’object’>

The next example describes a case of an unrecommended initialization. The C3 algorithm generates an error because
it cannot create a logical order:

1 # invalid_structure.py
2

3 class X():
4 def call_me(self):
5 print("I'm X")
6

8 class Y():
9 def call_me(self):
10 print("I'm Y")
11

12

13 class A(X, Y):


14 def call_me(self):
15 print("I'm A")
16
1.5. MULTIPLE INHERITANCE 25

17

18 class B(Y, X):


19 def call_me(self):
20 print("I'm B")
21

22

23 class F(A, B):


24 def call_me(self):
25 print("I'm F")
26

27 # TypeError: Cannot create a consistent method resolution


28 # order (MRO) for bases X, Y

Traceback (most recent call last):


File "/codes/invalid_structure.py",
line 24, in <module>
class F(A, B):
TypeError: Cannot create a consistent method resolution
order (MRO) for bases X, Y

A Multiple Inheritance Example

Here we present another case of multiple-inheritance, showing the wrong and the right way to call the initialization of
superclasses:

Wrong initialization of the superclass’ __init__ method

Calling directly to superclasses’ __init__ method inside the class Customer, as we show in the next example, is
highly not recommended. We could initiate a superclass multiple times, as we mentioned previously. In this example,
a call to object’s __init__ is done twice:

1 # inheritance_wrong.py
2

4 class AddressHolder:
5

6 def __init__(self, street, number, city, state):


26 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

7 self.street = street
8 self.number = number
9 self.city = city
10 self.state = state
11

12

13 class Contact:
14

15 contact_list = []
16

17 def __init__(self, name, email):


18 self.name = name
19 self.email = email
20 Contact.contact_list.append(self)
21

22

23 class Customer(Contact, AddressHolder):


24

25 def __init__(self, name, email, phone,


26 street, number, state, city):
27 Contact.__init__(self, name, email)
28 AddressHolder.__init__(self, street, number,
29 state, city)
30 self.phone = phone
31

32

33 if __name__ == "__main__":
34

35 c = Customer('John Davis', 'jp@g_mail.com', '23542331',


36 'Beacon Street', '231', 'Cambridge', 'Massachussets')
37

38 print("name: {}\nemail: {}\naddress: {}, {}"


39 .format(c.name, c.email, c.street, c.state))

name: John Davis


email: jp@g_mail.com
1.5. MULTIPLE INHERITANCE 27

address: Beacon Street, Massachussets

The right way: *args y **kwargs

Before showing the fixed version of the above example, we show how to use a list of arguments (*args) and keyword
arguments (**kwargs). In this case *args refers to a Non-keyword variable length argument list, where the
operator * unpacks the content inside the list args and pass them to a function as positional arguments.

1 # args_example.py
2

3 def method2(f_arg, *argv):


4 print("first arg normal: {}".format(f_arg))
5 for arg in argv:
6 print("the next arg is: {}".format(arg))
7

8 if __name__ == "__main__":
9 method2("Lorem", "ipsum", "ad", "his", "scripta")

first arg normal: Lorem


the next arg is: ipsum
the next arg is: ad
the next arg is: his
the next arg is: scripta

Similarly, **kwargs refers to a keyword variable-length argument list, where ** maps all the elements within the
dictionary kwargs and pass them to a function as non-positional arguments. This method is used to send a variable
amount of arguments to a function:

1 # kwargs_example.py
2

3 def method(arg1, arg2, arg3):


4 print("arg1: {}".format(arg1))
5 print("arg2: {}".format(arg2))
6 print("arg3: {}".format(arg3))
7

8
28 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

9 if __name__ == "__main__":
10 kwargs = {"arg3": 3, "arg2": "two"}
11 method(1, **kwargs)

arg1: 1
arg2: two
arg3: 3

Now that we know how to use *args and **kwargs, we can figure out how to properly write an example of
multiple inheritance as shown before:

1 # inheritance_right.py
2

4 class AddressHolder:
5

6 def __init__(self, street, number, city, state, **kwargs):


7 super().__init__(**kwargs)
8 self.street = street
9 self.number = number
10 self.city = city
11 self.state = state
12

13

14 class Contact:
15 contact_list = []
16

17 def __init__(self, name, email, **kwargs):


18 super().__init__(**kwargs)
19 self.name = name
20 self.email = email
21 Contact.contact_list.append(self)
22

23

24 class Customer(Contact, AddressHolder):


25
1.5. MULTIPLE INHERITANCE 29

26 def __init__(self, phone_number, **kwargs):


27 super().__init__(**kwargs)
28 self.phone_number = phone_number
29

30

31 if __name__ == "__main__":
32

33 c = Customer(name='John Davis', email='jp@g_mail.com',


34 phone_number='23542331', street='Beacon Street',
35 number='231', city='Cambridge', state='Massachussets')
36

37 print("name: {}\nemail: {}\naddress: {}, {}".format(c.name, c.email,


38 c.street, c.state))

name: John Davis


email: jp@g_mail.com
address: Beacon Street, Massachussets

As we can see in the above example, each class manage its own arguments passing the rest of the non-used arguments
to the higher classes in the hierarchy. For example, Customer passes all the non-used argument (**args) to
Contact and to AddressHolder through the super() function.

Polymorfism

Imagine that we have the ChessPiece class. This class has six subclasses: King, Queen, Rook, Bishop,
Knight, and Pawn. Each subclass contains the move method, but that method behaves differently on each subclass.
The ability to call a method with the same name but with different behavior within subclasses is called Polymorphism.
There are mainly two flavors of polymorphism:

• Overriding: occurs when a subclass implements a method that replaces the same method previously implemented
in the superclass.

• Overloading: happens when a method is implemented more than once, having a different number of arguments
on each case. Python does not support overloading because it is not really necessary. Each method can have a
variable number of arguments by using a keyworded o non-keyworded list of arguments. Recall that in Python
every time we implement a method more than once, the last version is the only one that Python will use. Other
30 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

programming languages support overloading, automatically detecting what method implementation to use
depending on the number of present arguments when the method is called.

The code bellow shows an example of Overriding. The Variable class represents data of any kind. The Income
class contains a method to calculate the representative value for it. In Income, the representative value is the average,
in City, the representative value is the most frequent city, and in JobTitle, the representative value is the job with
highest range, according to the _range dictionary:

1 # polymorfism_1.py
2

3 class Variable:
4 def __init__(self, data):
5 self.data = data
6

7 def representative(self):
8 pass
9

10

11 class Income(Variable):
12 def representative(self):
13 return sum(self.data) / len(self.data)
14

15

16 class City(Variable):
17 # class variable
18 _city_pop_size = {'Shanghai': 24000, 'Sao Paulo': 21300, 'Paris': 10800,
19 'London': 8600, 'Istambul': 15000,
20 'Tokyo': 13500, 'Moscow': 12200}
21

22 def representative(self):
23 dict = {City._city_pop_size[c]: c for c in self.data
24 if c in City._city_pop_size.keys()}
25 return dict[max(dict.keys())]
26

27

28 class JobTitle(Variable):
1.5. MULTIPLE INHERITANCE 31

29 # class variable
30 _range = {'CEO': 1, 'CTO': 2, 'Analyst': 3, 'Intern': 4}
31

32 def representative(self):
33 dict = {JobTitle._range[c]: c for c in self.data if
34 c in JobTitle._range.keys()}
35 return dict[min(dict.keys())]
36

37

38 if __name__ == "__main__":
39 income_list = Income([50, 80, 90, 150, 45, 65, 78, 89, 59, 77, 90])
40 city_list = City(['Shanghai', 'Sao Paulo', 'Paris', 'London',
41 'Istambul', 'Tokyo', 'Moscow'])
42 job_title_list = JobTitle(['CTO', 'Analyst', 'CEO', 'Intern'])
43 print(income_list.representative())
44 print(city_list.representative())
45 print(job_title_list.representative())

79.36363636363636
Shanghai
CEO

Operator Overriding

Python has several built-in operators that work for many of the built-in classes. For example, the operator “+” can
sum up two numbers, concatenate two strings, mix two lists, etc., depending on the object we are working with. The
following code shows an example:

1 # operator_overriding_1.py
2

3 a = [1, 2, 3, 4]
4 b = [5, 6, 7, 8]
5 print(a + b)
6

7 c = "Hello"
8 d = " World"
9 print(c + d)
32 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

[1, 2, 3, 4, 5, 6, 7, 8]
Hello World

Thanks to polymorphism, we can also personalize the method __add__ to make it work on any particular class we
want. For example, we may need to create a specific way of adding two instances of the ShoppingCart class in the
following code:

1 # operator_overriding_2.py
2

3 class ShoppingCart:
4

5 def __init__(self, product_list):


6 self.product_list = product_list # Python dictionary
7

8 def __call__(self, product_list = None):


9 if product_list is None:
10 product_list = self.product_list
11 self.product_list = product_list
12

13 def __add__(self, other_cart):


14 added_list = self.product_list
15 for p in other_cart.product_list.keys():
16 if p in self.product_list.keys():
17 value = other_cart.product_list[p] + self.product_list[p]
18 added_list.update({p: value})
19 else:
20 added_list.update({p: other_cart.product_list[p]})
21

22 return ShoppingCart(added_list)
23

24 def __repr__(self):
25 return "\n".join("Product: {} | Quantity: {}".format(
26 p, self.product_list[p]) for p in self.product_list.keys()
27 )
28

29
1.5. MULTIPLE INHERITANCE 33

30 if __name__ == "__main__":
31 s_cart_1 = ShoppingCart({'muffin': 3, 'milk': 2, 'water': 6})
32 s_cart_2 = ShoppingCart({'milk': 5, 'soda': 2, 'beer': 12})
33 s_cart_3 = s_cart_1 + s_cart_2
34 print(s_cart_3.product_list)
35 print(s_cart_3)

{’soda’: 2, ’water’: 6, ’milk’: 7, ’beer’: 12, ’muffin’: 3}


Product: soda | Quantity: 2
Product: water | Quantity: 6
Product: milk | Quantity: 7
Product: beer | Quantity: 12
Product: muffin | Quantity: 3

The __repr__ method allows us to generate a string that will be used everytime we ask to print any instance of
the class. We could also implement the __str__ method instead, it works almost exactly as __repr__, the main
difference is that __str__ should be used when we need a user friendly print of the object instance, related to the
particular context where it is used. The __repr__ method should generate a more detailed printing, containing all the
necessary information to understand the instance. In cases where __str__ and __repr__ are both implemented,
Python will use __str__ when print(instance) is called. Hence, __repr__ will be used only if __str__
is not implemented.

There are other operators that we can override, for example “less than” (__lt__), “greather than” (__gt__) and
“equal” (__eq__). We refer the reader to https://docs.python.org/3.4/library/operator.html
for a detailed list of built-in operators. Here is an example that shows how to override the __lt__ method for
implementing the comparison between two elements of the Point class:

1 # operator_overriding_3.py
2

3 class Point:
4

5 def __init__(self, x, y):


6 self.x = x
7 self.y = y
8

9 def __lt__(self, other_point):


34 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

10 self_mag = (self.x ** 2) + (self.y ** 2)


11 other_point_mag = (other_point.x ** 2) + (other_point.y ** 2)
12 return self_mag < other_point_mag
13

14 if __name__ == "__main__":
15 p1 = Point(2, 4)
16 p2 = Point(8, 3)
17 print(p1 < p2)

True

Duck Typing

The most common way to define it is "If it walks like a duck and quacks like a duck, then it is a duck." In other words,
it does not matter what kind of object performs the action, if it can do it, let it do it. Duck typing is a feature that
some programming languages have that makes polymorphism less attractive because it allows polymorphic behavior
without inheritance. In the next example, we can see that the activate function makes a duck scream and walk.
Despite that the method is implemented for Duck objects, it can be used with any object that has the scream and
walk methods implemented:

1 # duck_typing.py
2

4 class Duck:
5

6 def scream(self):
7 print("Cuack!")
8

9 def walk(self):
10 print("Walking like a duck...")
11

12

13 class Person:
14

15 def scream(self):
16 print("Ahhh!")
1.6. ABSTRACT BASE CLASS 35

17

18 def walk(self):
19 print("Walking like a human...")
20

21

22 def activate(duck):
23 duck.scream()
24 duck.walk()
25

26 if __name__ == "__main__":
27 Donald = Duck()
28 John = Person()
29 activate(Donald)
30 # this is not supported in other languajes, because John
31 # is not a Duck object
32 activate(John)

Cuack!
Walking like a duck...
Ahhh!
Walking like a human...

Typed programming languages that verify the type of objects during compilation time, such as C/C++, do not support
duck typing because in the list of arguments the object’s type has to be specified.

1.6 Abstract Base Class

Abstract classes in a programming language allow us to represent abstract objects better. What is an abstract object?
Abstract objects are created only to be inherited, so it does not make any sense to instantiate them. For example,
imagine that we have cars, buses, ships, and planes. Each one has similar properties (passengers capacity, color,
among others) and actions (load, move, stop) but they implement their methods differently: it is not the same to stop a
ship than a car. For this reason, we can create the class called Vehicle, to be a superclass of Car, Bus, Ship and
Plane.

Our problem now is how do we define Vehicle’s actions. We cannot define any of those behaviors inside Vehicle.
We can only do it inside any of its subclasses. That explains why it does not make any sense to instantiate the abstract
36 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

class Vehicle. Hence, it is recommended to make sure that abstract classes are not going to be instantiated in the
code, by raising an exception in case any programmer attempts to instantiate it.

We can also have abstract methods, in other words, methods that have to be defined in the subclasses because their
implementation makes no sense to occur in the abstract class. Abstract classes can also have traditional (non abstract)
methods when they do not need to be modified withing the subclasses. Let’s try to define abstract classes and abstract
methods in Python. The following code shows an example:

1 # 01_abstract_1.py
2

3 class Base:
4 def func_1(self):
5 raise NotImplementedError()
6

7 def func_2(self):
8 raise NotImplementedError()
9

10 class SubClass(Base):
11 def func_1(self):
12 print("func_1() called...")
13 return
14

15 # We intentionally did not implement func_2


16

17 b1 = Base()
18 b2 = SubClass()
19 b2.func_1()
20 b2.func_2()

func_1() called...
-----------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-17-0803174cce17> in <module>()
16 b2 = SubClass()
17 b2.func_1()
---> 18 b2.func_2()
1.6. ABSTRACT BASE CLASS 37

<ipython-input-17-0803174cce17> in func_2(self)
4
5 def func_2(self):
----> 6 raise NotImplementedError()
7
8 class SubClass(Base):

NotImplementedError:

The problem with this approach is that the program lets us instantiate Base without complaining, that is not what we
want. It also allows us not to implement all the needed methods in the subclass. An Abstract class allows the class
designer to assert that the user will implement all the required methods in the respective subclasses.

Python, unlike other programming languages, does not have a built-in way to declare abstract classes. Fortunately,
we can import the ABC module (stands for Abstract Base Class), that satisfies our requirements. The following code
shows an example:

1 # 03_ABC_1.py
2

3 from abc import ABCMeta, abstractmethod


4

6 class Base(metaclass=ABCMeta):
7 @abstractmethod
8 def func_1(self):
9 pass
10

11 @abstractmethod
12 def func_2(self):
13 pass
14

15

16 class SubClass(Base):
17 def func_1(self):
18 pass
19
38 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

20 # We intentionally did not implement func_2


21

22 print('Is it subclass?: {}'.format(issubclass(SubClass, Base)))


23 print('Is it instance?: {}'.format(isinstance(SubClass(), Base)))

Is it subclass?: True
-----------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-b1003dd6fd92> in <module>()
17
18 print(’Is it subclass?: {}’.format(issubclass(SubClass, Base)))
---> 19 print(’Is it instance?: {}’.format(isinstance(SubClass(), Base)))

TypeError: Can’t instantiate abstract class SubClass with abstract methods ’ \


’func_2

1 # 04_ABC_2.py
2

3 print('Trying to generate an instance of the Base class\n')


4 a = Base()

Trying to generate an instance of the Base class


---------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-e8aa694c9937> in <module>()
1 print(’Trying to generate an instance of the Base class\n’)
----> 2 a = Base()

TypeError: Can’t instantiate abstract class Base with abstract methods


func_1, func_2

Note that to declare a method as abstract we have to add the @abstractmethod decorator over its declaration. The
following code shows the implementation of the abstract methods:

1 # 05_ABC_3.py
2

3 from abc import ABCMeta, abstractmethod


1.7. CLASS DIAGRAMS 39

6 class Base(metaclass=ABCMeta):
7 @abstractmethod
8 def func_1(self):
9 pass
10

11 @abstractmethod
12 def func_2(self):
13 pass
14

15

16 class SubClass(Base):
17

18 def func_1(self):
19 pass
20

21 def func_2(self):
22 pass
23

24 # We forgot again to implement func_2


25

26 c = SubClass()
27 print('Subclass: {}'.format(issubclass(SubClass, Base)))
28 print('Instance: {}'.format(isinstance(SubClass(), Base)))

Subclass: True
Instance: True

1.7 Class Diagrams

By using class diagrams, we can visualize the classes that form most of the objects in our problem. Besides the classes,
we can also represent their properties, methods, and the way other classes interact with them. These diagrams belong
to a language known as Unified Modelling Language (UML). UML allows us to incorporate elements and tools to
model more complex systems, but it is out of the scope of this book. A class diagram is composed of a set of classes
40 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

and their relations. Rectangles represent classes, and they have three fields; the class name, its data (attributes and
variables), and its methods. Figure 1.2 shows an example.

Figure 1.2: UML Class diagram example

Suppose that by using OOP we want to model a database with stars that exist in a given area of the Universe. Each
star is correspond to a set of T observations, where each observation is a tuple (mi , ti , ei ), where mi is the bright
magnitude of the star in observation i, ti is the time when the observation i was obtained, and ei is the instrumental
error associated with observation i. Using UML diagrams, we can model the system as shown in figure 1.3.

Figure 1.3: UML tables for the stars model

Consider now that the TimeSeries class has methods to add an observation to the time series and to return the
average and standard deviation of the set of observations that belong to the star. We can represent the class and the
mentioned methods as in figure 1.4.

Besides the classes, we can represent the relations among them using UML notation as well. The most common types
of relations are: composition, agreggation and inheritance (Concepts explained previously in this chapter). Figure 1.5
shows an example of Composition. This relation is represented by an arrow starting from the base object towards the
target that the class is composing. The base of the connector is a black diamond. The number at the beginning and end
of the arrow represent the cardinalities, in other words, the range of the number of objects included in each side of the
relation. In this example, the number one at the beginning of the arrow and the 1, . . . , ∗ at the end, mean that one Time
Series may include a set of one or more observations, respectively.
1.7. CLASS DIAGRAMS 41

Figure 1.4: UML table for the TimeSeries class including the add_observation, average and
standard_deviation methods.

Figure 1.5: Example of the composition relation between classes in a UML diagram.

Similarly, agreggation is represented as an arrow with a hollow diamond at the base. Figure 1.6 shows an example. As
we learn previously in this chapter, here the only difference is that the database aggregates time series, but the time
series objects are entities that have a significance even out of the database where they are aggregate.

Figure 1.6: Example of the agreggation relation between classes in a UML diagram.
42 CHAPTER 1. OBJECT ORIENTED PROGRAMMING

In UML, we represent the inheritance as a simple arrow with a hollow triangle at the head. To show an example,
consider the case of astronomical stars again. Imagine that some of the time series are periodic. It means
that there is a set of values repeated at a constant amount of time. According to that, we can define the subclass
PeriodicTimeSeries that inherits from the TimeSeries class its common attributes and behaviors. Figure
1.7 shows this example in a UML diagram. The complete UML diagram for the astronomical stars example is shown
in figure 1.8.

Figure 1.7: Example of the inheritance relation between classes in a UML diagram.

Figure 1.8: The complete UML diagram for the astronomical stars example.
1.8. HANDS-ON ACTIVITIES 43

1.8 Hands-On Activities

Activity 1.1

Variable stars are stars whose level of brightness changes with time. They are of considerable interest in the
astronomical community. Each star belongs to one of the possible classes of variability. Some of the classes are RR
Lyrae, Eclipsing Binaries, Mira, Long Period Variables, Cepheids, and Quasars. Each star has a position in the sky
represented by RA and DEC coordinates. Stars are represented by an identifier and contain a set of observations. Each
observation is a tuple with three values: time, magnitude and error. Time value indicates the moment in which the
telescope or the instrument does the observation. The magnitude indicates the amount of brightness calculated in the
observation. The error corresponds to a range of uncertainty associated with the measurement. Many fields compose
the sky, and each field contains a huge amount of stars. For each star, we need to know the average and the variance
of the bright magnitudes. Create the necessary Python classes which allow modeling the situation described above.
Classes must have the corresponding attributes and methods. Write code to instantiate the classes involved.

Activity 1.2

A software company is building a computer program that works with geometric shapes and needs help with the initial
model. The company is interested in making the model as extensible as possible.

• Each figure has:

– A property center as an ordered pair (x,y). It should be possible to access and set it. The constructor
needs one to build a figure.

– A method translate that receives an ordered pair (a, b) and sums to each of the center’s component,
the components in (a, b).

– A property perimeter that should be calculated with the figure’s dimensions.

– A property area that should be calculated with the figure’s dimensions.

– A method grow_area that enlarges the area of the figure x times, increasing its dimensions proportionally.
For example, in the case of a rectangle it should modify its width y length.

– A method grow_perimeter that enlarges the perimeter in x units, increasing its dimensions propor-
tionally. For example, in the case of a rectangle it should modify its width y length.

– Each time a figure is printed, the output should have the following format:
ClassName - Perimeter: value, Area: value, Center: (x, y)
Another Random Scribd Document
with Unrelated Content
They thanked me heartily, I gave them some tracts, and told them if
it so pleased God I would come back to them and bring them some
more books, and try what could be done with some of the poor
children to make them better. I then left them and went to the East
Market, where there are many of all nations. The Jews and Spanish
looked at me very black. The colored people gathered around me, I
gave them little books and tracts, and told them I hoped to see
them again.
There are in this street upwards of a thousand young women and
children, living in sin of every kind. From thence I went to the jail,
where there were seventeen men, but no women. There were in the
House of Correction three hundred culprits; they are taken from
there, to work on plantations. I went to the Admiral's house, where
the emigrants find a shelter until they can find employment, then
they work and pay for their passage. Many leave their homes and
come to Jamaica under the impression that they are to have their
passage free, and on reaching the Island are to be found, until they
can provide for themselves.
How the mistake originated, I am not able to say, but on arriving
here, strangers poor and unacclimated, find the debt for passage
money hard and unexpected. It is remarkable that whether fresh
from Africa, or from other Islands from the South or from New
England, they all feel deceived on this point. I called on many
Americans and found them poor and discontented,—rueing the day
they left their country, where, notwithstanding many obstacles, their
parents lived and died, which they helped to conquer with their toil
and blood; now shall their children stray abroad and starve in foreign
lands.
There is in Jamaica an institution, established in 1836, called the
Mico Institution. It is named after its founder, Madame Mico, who
left a large sum of money to purchase, (or rather to ransom, the one
being a Christian act, the other a sin against the Holy Ghost, who
expressly forbids such traffic.) Madame Mico left this money to
ransom the English who were in bondage to the Algerines; if there
was any left, it was to be devoted to the instruction of the colored
people in the British Isles.
Beside the Mico establishment, there are in Jamaica twenty-seven
church missionary schools, where children are taught gratis. Whole
number taught, 952. London Missionary Society Schools, sixteen; the
number taught not ascertained. National Schools, thirty-eight. There
are also the Wesleyan, Presbyterian and Moravian Schools; it is
supposed there are private schools, where three or four thousand
are educated in the city of Kingston, and twice the number in the
street without the means of instruction. All the children and adults
taught in the above named schools, are taxed £1 a year, except the
English Church School, this is the most liberal. The Rev. Mr. Horton,
a Baptist minister in Kingston, told me he had sent ninety children
away from the Baptist school because they did not bring their
money. It is sufficient to say they had it not to bring!
Most of the people of Jamaica are emancipated slaves, many of
them are old, worn out and degraded. Those who are able to work,
have yet many obstacles to contend with, and very little to
encourage them; every advantage is taken of their ignorance; the
same spirit of cruelty is opposed to them as held them for centuries
in bondage; even religious teaching is bartered for their hard
earnings, while they are allowed but thirty-three cents a day, and are
told if they will not work for that they shall not work at all; an
extraordinary price is asked of them for every thing they may wish to
purchase, even their Bibles are sold to them at a large advance on
the first purchase. Where are their apologists, if they are found
wanting in the strict morals that Christians ought to practice? Who
kindly says, forgive them when they err? "Forgive them, this is the
bitter fruit of slavery." Who has integrity sufficient to hold the
balance when these poor people are to be weighed? Yet their
present state is blissful, compared with slavery.
Many of the farmers bring their produce twenty or thirty miles. Some
have horses or ponys, but most of them bring, their burdens on their
head. As I returned from St. Andrews's Mountain, where I had been
sent for by a Mr. Rose, I was overtaken by a respectable looking
man on horseback; we rode about ten miles in company. The story
he told me of the wrongs he and his wife had endured while in
slavery, are too horrible to narrate. My heart sickens when I think of
it. He asked me many questions, such as where I came from? why I
came to that Isle? where had I lived, &c? I told him I was sent for
by one of the missionaries to help him in his school. Indeed, said he,
our color need the instruction. I asked him why the colored people
did not hire for themselves? We would be very glad to, he replied,
but our money is taken from us so fast we cannot. Sometimes they
say we must all bring £1; to raise this, we have to sell at a loss or to
borrow, so that we have nothing left for ourselves; the Macroon
hunters take all—this is a nickname they give the missionaries and
the class-leaders—a cutting sarcasm this!
Arrived at a tavern, about a mile from Kingston, I bade the man
adieu, and stopped for my guide. The inn-keeper kindly invited me
in; he asked me several questions, and I asked him as many. How
do the people get along, said I, since the emancipation? The
negroes, he replied, will have the Island in spite of the d——. Do not
you see how they live, and how much they can bear? We cannot do
so. This man was an Englishman, with a large family of mulatto
children. I returned with my mind fully made up what to do. Spent
three weeks at the Mico establishment, and three with my colored
friends from America. We thought something ought to be done for
the poor girls that were destitute; they consulted with their friends,
called a meeting and formed a society of forty; each agreed to pay
three dollars a year and collect, and provide a house, while I came
back to America to raise the money for all needful articles for the
school. Here I met Mr. Ingraham for the first time; he had come
from the mountains, and his health had rapidly declined; wishing to
get his family home before the Lord took him away, he embarked for
Baltimore, in the Orb, and I sailed for Philadelphia, July 20th, 1841,
twenty-one days from Jamaica, in good health. I found there, Fitz W.
Sargent's family, from Gloucester, who I lived with when a little girl;
they received me very kindly, and gave donations of books and
money for that object.
I met the Anti Slavery Society at Mrs. Lucretia Motts, who took great
interest in the cause. I visited among the friends, and spent my time
very pleasantly. August 5th, I started for New York; arrived safely,
and staid with an old friend; ascertained that Mr. Ingraham's family
were at Newark, at Theodore Wells. He died four days after his
arrival. I was invited to Mrs. Ingraham's (his cousin's widow) to
spend a week. There I met with much encouragement to labor in
the cause. Missionaries were coming and going, and all seemed to
be interested in my object. Saturday evening I went to the bath
room, where I left my neck ribbon: returning after it, I had the
misfortune to fall through an open trap door, down fifteen feet, on
hard coal. I had no light with me. I dislocated my left shoulder, and
was generally very much bruised; my screams brought the girl to my
assistance, and by the help of God she brought me out of the cellar;
it was some time before a surgeon could be procured; at last Dr.
Jossleyn came to my relief, he set my shoulder. I was obliged to
remain at Mrs. Ingraham's three weeks; as soon as I was able I left
there for Boston. I intended to have gone by the western boat, but
by mistake got on board Captain Comstock's, and was exposed on
deck all night in a damp east wind, and when I arrived at the
landing I could not assist myself; a sailor who saw and pitied my
situation, kindly took care of me and my baggage, and on my arrival
in Boston procured a carriage for me. If it had not been for his
kindness I know not how I should have got along.
As soon as I was able I commenced my task of collecting funds for
my Free Labor School in Jamaica. I collected in Boston and vicinity,
in New York and Philadelphia, but not sufficient to make up the
required sum, and I was obliged to take fifty dollars from my own
purse, thinking that when I returned to Jamaica they would refund
the money to me. April 15th, embarked on board the Brig Norma, of
New York, for Jamaica. I arrived at Kingston May 6th, and found
every thing different from what it was when I left; the people were
in a state of agitation, several were hanged, and the insurrection
was so great that it was found necessary to increase the army to
quell it. Several had been hanged. On the very day I arrived a man
was hanged for shooting a man as he passed through the street.
Such was the state of things that it was not safe to be there.
A few young people met to celebrate their freedom on an open
plain, where they hold their market; their former masters and
mistresses envious of their happiness, conspired against them and
thought to put them down by violence. This only served to increase
their numbers; but the oppressors were powerful and succeeded in
accomplishing their revenge, although many of them were relations.
There was a rule among the slave holders, to take care of the
children they have by their slaves; they select them out and place
them in asylums. Those who lived with their white fathers were
allowed great power over their slave mothers and her slave children;
my heart was often grieved to see their conduct to their poor old
grand parents. Those over twenty-one were freed in 1834, all under
twenty-one, were to serve their masters till twenty-one. It is well
known that at that time, the children alike with others, received
twenty-five dollars a head for their relatives. Were I to tell all my
eyes have seen among that people it would not be credited. It is
well known that those that were freed, knowing their children were
still in bondage, were not satisfied. In the year 1838, general
freedom throughout the British Islands gave the death blow to the
power of the master, and mothers received with joy their
emancipated children; they no longer looked the picture of despair,
fearing to see their mulatto son or daughter, beating or abusing their
younger brothers and sisters of a darker skin. On this occasion there
was an outrage committed by those who were in power. What little
the poor colored people had gathered during their four years of
freedom, was destroyed by violence; their fences were broken down,
and their horses and hogs taken from them. Most of the mulattoes
and masters are educated, many of them are very poor, some are
very rich; the property is left to the oldest daughter, she divides it
with her brothers and sisters; since slavery ended many of them
have married; those who are poor, and mean to live in sin, make for
New Orleans and other slave States; many of the planters left the
Island when slavery was abolished. In June, 1841, a number of
people arrived from Sierra Leone at Jamaica; these were Maroons
who were banished from the Island. They were some of the original
natives who inhabited the mountains, and were determined to
destroy the whites. These Maroons would secrete themselves in
trees, and arrest the whites as they passed along, they would
pretend to guide them, when they would beat and abuse them as
the whites did their slaves; the English finding themselves defeated
in all their plans to subdue them, proposed to take them by craft.
They made a feast in a large tavern in Kingston, and invited them to
come; after they had eaten, they were invited on board three ships
of war, that were all ready to set sail for Sierra Leone; they were
many of them infants in their mother's arms, they were well taken
care of by the English and instructed; they were removed about the
year 1796—they are bright and intelligent, I saw and conversed with
them; when they heard of the abolition of slavery, they sent a
petition to Queen Victoria that they might return to Jamaica, which
was granted. Several of them were very old when they returned;
they were men and women when they left the Island, they had not
forgot the injuries they had received from the hands of man, nor the
mercies of God to them, nor his judgments to their enemies. Their
numbers were few but their power was great; they say the Island, of
right, belongs to them. Had their been a vessel in readiness I should
have come back immediately, it seemed useless to attempt to
establish a Manual Labor School, as the government was so
unsettled that I could not be protected. Some of my former friends
were gone as teachers to Africa, and some to other parts of the
Island. I called on the American Consul to consult with him, he said
that although such a school was much wanted, yet every thing
seemed so unsettled that I had no courage to proceed. I told him
there was so much excitement that I wished to leave the Island as
soon as he could find me a passage, it seemed useless to spend my
time there. As soon as it was known that I intended to return, a
movement was made to induce me to remain. I was persuaded to
try the experiment for three months, not thinking their motive was
bad. Before I left the United States, I got all that was needed, within
fifty dollars. The fifty dollars I supplied from my own purse,
expecting they would pay me. It cost me ten dollars for freight, and
twenty-five for passage money; these people that I had hoped to
serve, were much taken up with the things I had brought, they
thought that I had money and I was continually surrounded; the
thought of color was no where exhibited, much notice was taken of
me. I was invited to breakfast in one place, and to dine in another,
&c. A society was organized, made up of men and women of
authority. A constitution was drafted by my consent, by those who
were appointed to meet at my rooms. Between the time of the
adjournment they altered it to suit themselves. At the time
appointed we came together with a spirit apparently becoming any
body of Christians; most of them were members of Christian
churches; the meeting was opened with reading the Scriptures and
prayer. Then said the leader, since our dear sister has left her native
land and her friends to come to us, we welcome her with our hearts
and hands. She will dwell among us, and we will take care of her—
Brethren think of it!, after which he sat down, and the constitution
was called for. The Preamble held out all the flattery that a fool could
desire; after which they commenced the articles, supposing that
they could do as they thought best. The fourth article unveiled their
design. As we have designed to take care of our sister, we the
undersigned will take charge of all she has brought; the vote was
called, every person rose in a moment except myself: every eye was
upon me; one asked me why I did not vote, I made no answer—
they put the vote again and again, I remained seated; well said the
President, we can do nothing without her vote; they remained some
time silent, and then broke up the meeting. The next day the
Deacon called to see what the state of my mind was, and some of
the women proposed that we should have another meeting. I told
them no, I should do no more for them. As soon as they found they
could not get the things in the way they intended, they started to
plunder me; but I detected their design, and was on my guard, I
disposed of the articles, and made ready to leave when an
opportunity presented. A more skilful plan than this Satan never
designed, but the power of God was above it. It is not surprising
that this people are full of deceit and lies, this is the fruits of slavery,
it makes master and slaves knaves. It is the rule where slavery exists
to swell the churches with numbers, and hold out such doctrines, as
obedience to tyrants, is a duty to God. I went with a Baptist woman
to the house of a minister of the Church of England, to have her
grandchild christened before it died; she told me if she did not have
it christened, it would rise up in judgment against her. This poor
deluded creature was a class leader in the Baptist Church, and such
is the condition of most of the people: they seemed blinded to every
thing but money. They are great for trade, and are united in their
determination for procuring property, of which they have amassed a
vast amount. Notwithstanding I had made over various articles to
one of the American Missionaries, a Mr. J. S. Beadslee, of Clarendon
Mountains, I also gave to others where they were needed, which
receipts and letters I have in my possession. Notwithstanding all
this, they made another attempt to rob me, and as a passage could
not be obtained for me to return home, I was obliged to go to the
Mico establishment again for safety, such was the outrage. Houses
were broken open and robbed every night. I came very near being
shot: there was a certain place where we placed ourselves the first
of the evening. A friend came to bring us some refreshments, I had
just left the window when a gun was fired through it, by one that
often sat with us; this was common in the time of slavery. Previous
to vessels arriving, passages were engaged. I disposed of my articles
and furniture at a very small profit. On the 1st of August, Capt. A.
Miner arrived, and advertised for passengers. The American Consul
procured me a passage, and on the 18th of August myself and nine
other passengers embarked for New York.
I might have diversified my book with more extended descriptions of
Jamaica, with its tropical climate and productions, and contrasted it
with Northern Russia. I hope my readers will not think that I was
unmoved by all the wonders and beauties of nature, that were
presented to me in various climes. Before giving an account of the
voyage from Jamaica, it may prove interesting to some readers, to
have a brief description of the country. With her liberty secured to
her, may she now rise in prosperity, morality and religion, and
become a happy people whose God is the Lord.

WEST INDIES.
A denomination under which is comprehended a large chain of
islands, extending in a curve from the Florida shore on the northern
peninsula of America, to the Gulf of Venezuela on the southern.
These islands belong to five European powers, viz: Great Britain,
Spain, France, Holland, and Denmark. An inhabitant of New England
can form no idea of the climate and the productions of these islands.
Many of the particulars that are here mentioned, are peculiar to
them all.
The climate in all the West India Islands is nearly the same, allowing
for those accidental differences which the several situations and
qualities of the lands themselves produce; as they lie within the
tropic of Cancer, and the sun is often almost at the meridian over
their heads, they are continually subjected to a heat that would be
intolerable but for the trade winds, which are so refreshing as to
enable the inhabitants to attend to their various occupations, even
under a noonday sun; as the night advances, a breeze begins to be
perceived, which blows smartly from the land, as it were from the
centre towards the sea, to all points of the compass at once. The
rains make the only distinction of seasons on these islands. The
trees are green the year round; they have no cold or frost; our
heaviest rains are but dews comparatively; with them floods of water
are poured from the clouds. About May, the periodical rains from the
South may be expected. Then the tropical summer, in all its splendor,
makes its appearance. The nights are calm and serene, the moon
shines more brightly than in New England, as do the planets and the
beautiful galaxy. From the middle of August to the end of September
the heat is most oppressive, the sea breeze is interrupted, and calms
warn the inhabitants of the periodical rains, which fall in torrents
about the first of October.
The most considerable and valuable of the British West India
Islands, lies between the 75th and the 79th degrees of west
longitude from London, and between 17 and 18 north latitude; it is
of an oval figure, 150 miles long from east to west, sixty miles broad
in the middle, containing 4,080,000 acres. An elevated ridge, called
the Blue Mountains, runs lengthwise from east to west, whence
numerous rivers take their rise on both sides. The year is divided
into two seasons, wet and dry. The months of July, August, and
September, are called the hurricane months. The best houses are
generally built low, on account of the hurricanes and earthquakes.
However pleasant the sun may rise, in a moment the scene may be
changed; a violent storm will suddenly arise, attended with thunder
and lightning; the rain falls in torrents, and the seas and rivers rise
with terrible destruction. I witnessed this awful scene in June last, at
Kingston, the capital of Jamaica; the foundations of many houses
were destroyed; the waters, as they rushed from the mountains,
brought with them the produce of the earth, large branches of trees,
together with their fruit; many persons were drowned, endeavoring
to reach their homes; those who succeeded, were often obliged to
travel many miles out of their usual way. Many young children,
without a parent's care, were at this time destroyed. A poor old
woman, speaking of these calamities to me, thus expressed herself:
"Not so bad now as in the time of slavery; then God spoke very loud
to Bucker, (the white people,) to let us go. Thank God, ever since
that they give us up, we go pray, and we have it not so bad like as
before." I would recommend this poor woman's remark to the fair
sons and daughters of America, the land of the pilgrims, "Then God
spoke very loud." May these words be engraved on the post of every
door in this land of New England. God speaks very loud, and while
his judgments are on the earth, may the inhabitants learn
righteousness!
The mountains that intersect this island, seem composed of rocks,
thrown up by frequent earthquakes or volcanoes. These rocks,
though having little soil, are adorned with a great variety of beautiful
trees, growing from the fissures, which are nourished by frequent
rains, and flourish in perpetual spring. From these mountains flow a
vast number of small rivers of pure water, which sometimes fall in
cataracts, from stupendous heights; these, with the brilliant verdure
of the trees, form a most delightful landscape. Ridges of smaller
mountains are on each side of this great chain; on these, coffee
grows in great abundance; the valleys or plains between these
ridges, are level beyond what is usually found in similar situations.
The highest land in the island is Blue Mountain Peak, 7150 feet
above the sea. The most extensive plain is thirty miles long and five
broad. Black river, in the Parish of St. Elizabeth, is the only one
navigable; flat-boats bring down produce from plantations about
thirty miles up the river. Along the coast, and on the plains, the
weather is very hot; but in the mountains the air is pure and
wholesome; the longest days in summer are about thirteen hours,
and the shortest in winter about eleven. In the plains are found
several salt fountains, and in the mountains, not far from Spanish
Town, is a hot bath of great medicinal virtues; this gives relief in the
complaint called the dry bowels malady, which, excepting the bilious
and yellow fevers, is one of the most terrible distempers of Jamaica.
The general produce of this island is sugar, rum, molasses, ginger,
cotton, indigo, pimento, cocoa, coffees, several kinds of woods, and
medicinal drugs. Fruits are in great plenty, as oranges, lemons,
shaddoks, citrons, pomegranates, pineapples, melons, pompions,
guavas, and many others. Here are trees whose wood, when dry, is
incorruptible; here is found the wild cinnamon tree, the mahogany,
the cabbage, the palm, yielding an oil much esteemed for food and
medicine. Here, too, is the soap tree, whose berries are useful in
washing. The plantain is produced in Jamaica in abundance, and is
one of the most agreeable and nutritious vegetables in the world: it
grows about four feet in height, and the fruit grows in clusters,
which is filled with a luscious sweet pulp. The Banana is very similar
to the plantain, but not so sweet. The whole island is divided into
three counties, Middlesex, Surry, and Cornwall, and these into six
towns, twenty parishes, and twenty-seven villages.
This island was originally part of the Spanish Empire in America, but
it was taken by the English in 1656. Cromwell had fitted out a
squadron under Penn and Venables, to reduce the Spanish Island of
Hispaniola; but there this squadron was unsuccessful, and the
commanders, of their own accord, to atone for this misfortune,
made a descent on Jamaica, and having arrived at St. Jago, soon
compelled the whole island to surrender.
Ever since, it has been subject to the English, and the government,
next to that of Ireland, is the richest in the disposal of the crown.
Port Royal was formerly the capital of Jamaica; it stood upon the
point of a narrow neck of land, which, towards the sea, forms part of
the border of a very fine harbor of its own name. The conveniences
of this harbor, which was capable of containing a thousand sail of
large ships, and of such depth as to allow them to load and unload
with the greatest ease, weighed so much with the inhabitants, that
they chose to build their capital on this spot, although the place was
a hot, dry sand, and produced none of the necessaries of life, not
even fresh water. About the beginning of the year 1692, no place for
its size could be compared to this town for trade, wealth, and an
entire corruption of manners. In the month of June in this year, an
earthquake which shook the whole island to the foundation, totally
overwhelmed this city, so as to leave, in one quarter, not even the
smallest vestige remaining. In two minutes the earth opened and
swallowed up nine-tenths of the houses, and two thousand people.
The waters gushed out from the openings of the earth, and the
people lay as it were in heaps: some of them had the good fortune
to catch hold of beams and rafters of houses, and were afterwards
saved by boats. Several ships were cast away in the harbor, and the
Swan Frigate, which lay in the Dock, was carried over the tops of
sinking houses, and did not overset, but afforded a retreat to some
hundreds of people, who saved their lives upon her. An officer who
was in the town at that time, says the earth opened and shut very
quick in some places, and he saw several people sink down to the
middle, and others appeared with their heads just above ground,
and were choked to death. At Savannah above a thousand acres
were sunk, with the houses and people in them, the place
appearing, for some time, like a lake; this was afterwards dried up,
but no houses were seen. In some parts mountains were split, and
at one place a plantation was removed to the distance of a mile. The
inhabitants again rebuilt the city, but it was a second time, ten years
after, destroyed by a great fire. The extraordinary convenience of the
harbor tempted them to build it once more, and in 1722 it was laid
in ruins by a hurricane, the most terrible on record.
Such repeated calamities seemed to mark out this spot as a devoted
place; the inhabitants, therefore, resolved to forsake it forever, and
to reside at the opposite bay, where they built Kingston, which is
now the capital of the island. In going up to Kingston, we pass over
a part of and between Port Royal, leaving the mountains on the left,
and a small town on the right. There are many handsome houses
built there, one story high, with porticos, and every convenience for
those who inhabit them. Not far from Kingston stands Spanish Town,
which, though at present far inferior to Kingston, was once the
capital of Jamaica, and is still the seat of government.
On the 3d of October, 1780, there was a dreadful hurricane, which
overwhelmed the little seaport town of Savannah, in Jamaica, and
part of the adjacent country; very few houses were left standing,
and a great number of lives were lost; much damage was done also,
and many lives lost, in other parts of the island.
In January, 1823, a society was formed in London for mitigating and
gradually abolishing slavery, throughout the British dominions, called
the Anti-Slavery Society. His Royal Highness, the Duke of Gloucester,
was President of the Society; in the list of Vice Presidents are the
names of many of the most distinguished philanthropists of the day,
and among them that of the never to be forgotten Mr. Wilberforce;
as a bold champion, we see him going forward, pleading the cause
of our down-trodden brethren. In the year 1834, it pleased God to
break the chains from 800,000 human beings, that had been held in
a state of personal slavery; and this great event was effected
through the instrumentality of Clarkson, Wilberforce, and other
philanthropists of the day.
The population of Jamaica is nearly 400,000; that of Kingston, the
capital, 40,000. There are many places of worship of various
denominations, namely, Church of England, and of Scotland,
Wesleyan, the Baptist, and Roman Catholics, besides a Jewish
Synagogue. These all differ from what I have seen in New England,
and from those I have seen elsewhere. The Baptist hold what they
call class-meetings. They have men and women, deacons and
deaconesses in these churches; these hold separate class-meetings;
some of these can read, and some cannot. Such are the persons
who hold the office of judges, and go round and urge the people to
come to the class, and after they come in twice or three times, they
are considered candidates for baptism. Some pay fifty cents, and
some more, for being baptized; they receive a ticket as a passport
into the church, paying one mark a quarter, or more, and some less,
but nothing short of ten pence, that is, two English shillings a year.
They must attend their class once a week, and pay three pence a
week, total twelve English shillings a year, besides the sums they pay
once a month at communion, after service in the morning. On those
occasions the minister retires, and the deacons examine the people,
to ascertain if each one has brought a ticket; if not, they cannot
commune; after this the minister returns, and performs the
ceremony, then they give their money and depart. The churches are
very large, holding from four to six thousand; many bring wood and
other presents to their class-leader, as a token of their attachment;
where there are so many communicants, these presents, and the
money exacted, greatly enrich these establishments. Communicants
are so ignorant of the ordinance, that they join the church merely to
have a decent burial; for if they are not members, none will follow
them to the grave, and no prayers will be said over them; these are
borne through the streets by four men, the coffin a rough box; not
so if they are church members; as soon as the news is spread that
one is dying, all the class, with their leader, will assemble at the
place, and join in singing hymns; this, they say, is to help the spirit
up to glory; this exercise sometimes continues all night, in so loud a
strain, that it is seldom that any of the people in the neighborhood
are lost in sleep.
After leaving Jamaica, the vessel was tacked to a south-west course.
I asked the Captain what this meant. He said he must take the
current, as there was no wind. Without any ceremony, I told him it
was not the case, and told the passengers that he had deceived us.
There were two English men that were born on the island, that had
never been on the water; before the third day passed, they asked
the Captain why they had not seen Hayti. He told them they passed
when they were asleep. I told them it was not true, he was steering
south south-west. The passengers in the steerage got alarmed, and
every one was asking the Captain what this meant. The ninth day
we made land. "By ——," said the Captain, "this is Key West; come,
passengers, let us have a vote to run over the neck, and I will go
ashore and bring aboard fruit and turtle." They all agreed but myself.
He soon dropped anchor. The officers from the shore came on board
and congratulated him on keeping his appointment, thus proving
that my suspicions were well founded. The Captain went ashore with
these men, and soon came back, called for the passengers, and
asked for their vote for him to remain until the next day, saying that
he could, by this delay, make five or six hundred dollars, as there
had been a vessel wrecked there lately. They all agreed but myself.
The vessel was soon at the side of the wharf. In one hour there
were twenty slaves at work to unload her; every inducement was
made to persuade me to go ashore, or set my feet on the wharf. A
law had just been passed there that every free colored person
coming there, should be put in custody on their going ashore; there
were five colored persons on board; none dared to go ashore,
however uncomfortable we might be in the vessel, or however we
might desire to refresh ourselves by a change of scene. We
remained at Key West four days.
September 3d we set sail for New York, at 3 o'clock in the afternoon.
At 10 o'clock a gale took us, that continued thirty-six hours; my
state-room was filled with water, and my baggage all upset; a
woman, with her little boy, and myself, were seated on a trunk
thirty-six hours, with our feet pressed against a barrel to prevent
falling; the water pouring over us at every breaker. Wednesday, the
9th, the sun shone out, so that the Captain could take an
observation. He found himself in great peril, near the coast of Texas.
All hands were employed in pumping and bailing. On the eleventh,
the New Orleans steamer came to our assistance; as we passed up
the river, I was made to forget my own condition, as I looked with
pity on the poor slaves, who were laboring and toiling, on either
side, as far as could be seen with a glass. We soon reached the
dock, and we were there on the old wreck a spectacle for
observation; the whites went on shore and made themselves
comfortable, while we poor blacks were obliged to remain on that
broken, wet vessel. The people were very busy about me; one man
asked me who I belonged to, and many other rude questions; he
asked me where I was born; I told him Newburyport. "What were
your parents' names?" I told him my father's name was Thomas
Gardener; his countenance changed; said he, "I knew him well;" and
he proved friendly to me. He appeared very kind, and offered to
arrange my affairs so that I might return to New York through the
States. I thought it best to decline his proposal, knowing my spirit
would not suffer me to pass on, and see my fellow-creatures
suffering without a rebuke. We remained four days on the wreck;
the boxes that contained the sugar were taken out; the two bottom
tiers were washed out clean. There were a great many people that
came to see the vessel; they were astonished that she did not sink;
they watched me very closely. I asked them what they wished. In
the mean time, there came along a drove of colored people, fettered
together in pairs by the wrist; some had weights, with long chains at
their ankles, men and women, young and old. I asked them what
that meant. They all were ready to answer. Said they, "these negroes
have been impudent, and have stolen; some of them are free
negroes from the northern ships;" "and what," I asked, "are they
there for?" "For being on shore, some of them at night." I asked
them who made them Lord over God's inheritance. They told me I
was very foolish; they should think I had suffered enough to think of
myself. I looked pretty bad, it is true; I was seated on a box, but
poorly dressed; the mate had taken my clothes to a washer-woman;
why he took this care, he was afraid to send the cook or steward on
shore, as they were colored people. I kept still; but the other woman
seemed to be in perfect despair, running up and down the deck,
ringing her hands and crying, at the thought of all her clothes being
destroyed; then her mind dwelt upon other things, and she seemed
as if she were deranged; she took their attention for a few minutes,
as she was white. Soon the washer-woman came with my clothes;
they spoke to her as if she had been a dog. I looked at them with as
much astonishment as if I had never heard of such a thing. I asked
them if they believed there was a God. "Of course we do," they
replied. "Then why not obey him?" "We do." "You do not; permit me
to say there is a God, and a just one, that will bring you all to
account." "For what?" "For suffering these men that have just come
in to be taken out of these vessels, and that awful sight I see in the
streets." "O that is nothing; I should think you would be concerned
about yourself." "I am sure," I replied, "the Lord will take care of
me; you cannot harm me." "No, we do not wish to; we do not want
you here." Every ship that comes in, the colored men are dragged to
prison. I found it necessary to be stern with them; they were very
rude; if I had not been so, I know not what would have been the
consequences. They went off for that day; the next day some of
them came again. "Good morning," said they; "we shall watch you
like the d—— until you go away; you must not say any thing to
these negroes whilst you are here." "Why, then, do you talk to me, if
you do not want me to say any thing to you? If you will let me
alone, I will you." "Let me see your protection," they replied, "they
say it is under the Russian government." I pointed them to the
eighteenth chapter of Revelations and fifteenth verse: "The
merchants of these things which were made rich by her, shall stand
afar off, for the fear of her torment, weeping and wailing. For strong
is the Lord God who judgeth her." They made no answer, but asked
the Captain how soon he should get away.
On the 17th, the Captain put eight of us on board the bark H. W.
Tyler, for New York; we had about a mile to walk; the Captain was in
honor bound to return us our passage money, which we had paid
him at Jamaica; he came without it to see if we were there, and
went away saying he would soon return with it; but we saw no more
of him or our money! Our bark, and a vessel loaded with slaves,
were towed down the river by the same steamer; we dropped
anchor at the bottom of the bay, as a storm was rising. The 18th, on
Sabbath, it rained all day. Captain Tyler knocked at my door, wishing
me to come out; it rained hard; the bulwork of the bark was so high
I could not look over it; he placed something for me to stand on,
that I might see the awful sight, which was the vessel of slaves
laying at the side of our ship; the deck was full of young men, girls
and children, bound to Texas for sale! Monday, the 19th, Captain
Tyler demanded of us to pay him for our passage. I had but ten
dollars, and was determined not to give it; he was very severe with
all. I told him there were articles enough to pay him belonging to
me. Those who had nothing, were obliged to go back in the steamer.
Tuesday, the 20th, we set sail; the storm was not over. The 22d the
gale took us; we were dismasted, and to save sinking, sixty casks of
molasses were stove in, and holes cut in the bulworks to let it off; all
the fowls, pigs, and fresh provisions, were lost. We were carried
seventy-five miles up the bay of Mexico. The Captain was
determined not to pay the steamer for carrying him back to New
Orleans, and made his way the best he could.
The 3d of October we arrived again at Key West. The Captain got
the bark repaired, and took on board a number of turtles, and a
plenty of brandy. Friday, the 7th, set sail for New York; the Captain
asked me why I did not go ashore when there in the Comet; "had
you," said he, "they intended to beat you. John and Lucy Davenport,
of Salem, laid down the first ten dollars towards a hundred for that
person who should get you there." The Florida laws are about the
same as those at New Orleans. He was very talkative; wished to
know if I saw any thing of the Creole's crew while at Jamaica. I told
him they were all safe, a fine set of young men and women; one
dear little girl, that was taken from her mother in Virginia, I should
have taken with me, if I had had the money. He said his brother
owned the Creole, and some of the slaves were his. "I never owned
any; I have followed the sea all my life, and can tell every port and
town in your State."
October 19th, 1842, arrived at New York, and thankful was I to set
my feet on land, almost famished for the want of food; we lost all of
our provisions; nothing was left but sailors' beef, and that was
tainted before it was salted. I went at once to those who professed
to be friends, but found myself mistaken. I hardly knew what was
best. I had put up at Mrs. Raweses; she did all she could to raise the
twenty-five dollars that I must pay before I could take my baggage
from the vessel. This seemed hard to obtain; I travelled from one to
another for three days; at last I called at the Second Advent office;
Mr. Nath'l Southard left his business at once, and took me to Mr.
Lewis Tappan and others; they raised the money, and went with me
to the ship after my baggage. It was three o'clock on Saturday
afternoon when I called on Mr. Southard; the vessel and Captain
belonged to Virginia, was all ready for sea, waiting for a wind; they
had ransacked my things. I took from Jamaica forty dollar's worth of
preserved fruits; part were lost when we were cast away in the
Cornet, and some they had stolen. At eight o'clock on Saturday
evening, I made out to have my things landed on the wharf; it was
very dark, as it rained hard. My kind friend did not leave me until
they were all safely lodged at my residence. I boarded there three
weeks, thinking to come home; but it was thought best for me to
wait, and see if Captain Miner came or not, hoping that I might
recover my loss through him. I took a room and went to sewing, and
found the people very kind.
February, 1843, the colored men that went back to New Orleans, for
the want of passage money, arrived at New York, wearied out. All
the white people remained there. I waited in New York until the last
of July, when I started for Boston. August 1st, 1843, arrived, poor in
health and poor in purse, having sacrificed both, hoping to benefit
my fellow-creatures. I trust it was acceptable to God, who in his
providence preserved me in perils by land and perils by sea.

"God moves in a mysterious way


His wonders to perform;
He plants his footsteps on the sea,
And rides upon the storm.

"Deep in unfathomable mines


Of never-failing skill,
He treasures up his bright designs,
And works his sovereign will."

Having lost all, I determined, by the help of God, to leave the event;
some of my friends in this city sympathized with me, and others took
the advantage to reproach me. But in the hands of the Lord there is
a cup; the Saviour drank it to the dregs. They gather themselves
together; they hide themselves; they mark my steps; they waited for
my soul, but the Lord is my defence, the Holy One of Israel is my
Saviour. I'll trust him for strength and defence. What things were
gain to me, I counted loss for Christ, for whom I have suffered all
things; and do count them nothing, that I may win Christ and be
found in him, not having mine own righteousness, which is of the
Lord, but that which is through the faith of Christ, that which is of
God by faith, that I may know him, and the power of his
resurrection, and the fellowship of his sufferings, being made
conformable unto his death, strengthened with all might, according
to his glorious power, unto all patience and long-suffering, with
joyfulness, thinking it not strange concerning the fiery trials, as
though some strange thing happened; for saith the apostle, it is
better if the will of God so be that ye suffer for well doing, than for
evil; they think it strange that ye run not with them to the same
excess of riot, speaking evil of you. If they do these things in a
green tree, what shall be done in a dry?

"I hate to walk, I hate to sit


With men of vanity and lies;
The scoffer and the hypocrite
Are the abhorrence of my eyes.

God knows their impious thoughts are vain,


And they shall feel his power;
His wrath shall pierce their souls with pain,
In some surprising hour."

The first twenty months after my arrival in the city, notwithstanding


my often infirmities, I labored with much success, until I hired with
and from those whom I mostly sympathized with, and shared in
common the disadvantages and stigma that is heaped upon us, in
this our professed Christian land. But my lot was like the man that
went down from Jerusalem and fell among thieves, which stripped
him of his raiment, and wounding him departed, leaving him half
dead. What I did not lose when cast away, has been taken from my
room where I hired. Three times I had been broken up in business,
embarrassed and obliged to move, when not able to wait on myself.
This has been my lot. In the midst of my afflictions, sometimes I
have thought my case like that of Paul's, when cast among wild
beasts. "Had not the Lord been on my side, they would have
swallowed me up; but blessed be the Lord who hath not given me a
prey to their teeth."
In 1848 and '49, the Lord was pleased to lay his hand upon me.
Some of my friends came to my relief; but the promises of God were
neither few nor small; he knows them that trust and fear him, and in
his providence had reserved the good Samaritan. One of my
unretired friends made my case known to the Rev. Dr. Bigelow and
wife, who sought me out in my distress. I shall not soon forget the
morning she came to me, with an expression of love and kindness,
wishing to know my case. Mrs. Bigelow was the daughter of Captain
Theodore Stanwood, of Gloucester, whom Mr. Prince sailed with as
steward the first time he went to Russia. Mrs. B. is one of the kind
friends I speak of, when carried to Gloucester sick, in 1814; she was
then a little miss. A friend of mine lived with her mother; she used to
say that Amelia would not rest, when she came from school, till she
had something to bring to my mother and me. Mrs. Bigelow and
family were very kind, doing all in their power to make me
comfortable, and even moved me from the house of the tyrant that I
then hired from, and raised me up other kind friends; and, with the
blessing of God and the counsel of Dr. Grey, my health is much
improved. "I am as a wonder unto many, but the Lord is my strong
refuge." Underneath him is the everlasting arm of mercy; misfortune
is never mournful for the soul that accepts it, for such do always see
that every cloud is an angel's face; sorrow connects the soul with
the invisible.
O Father, fearful indeed is this world's pilgrimage, when the soul has
learned that all its sounds are echos, all its sights are shadows. But
lo! a cloud opens, a face serene and hopeful looks forth and saith,
"Be thou as a little child, and thus shalt thou become a seraph, and
bow thyself in silent humility and pray, not that afflictions might not
visit, but be willing to be purified through fire, and accept it meekly."
DIVINE CONTENTMENT.
Advancement of Faith is Necessary.
All our disquietnesses do issue immediately from unbelief. It is this
that raiseth the storm of discontent in the heart. Oh, set faith at
work! It is the property of faith to silence our doubtings, to scatter
our fears, to still the heart when the passions are up. Faith works
the heart to a sweet serene composure: it is not having food and
raiment, but having faith, which will make us content. Faith chides
down passion; when Reason begins to swim, let Faith swim.
Quest. How doth Faith work contentment?
Answ. 1. Faith shows the soul that whatever its trials are, yet it is
from the hand of a kind Father: it is indeed a bitter cup; but "shall I
not drink the cup which my Father hath given me to drink?" (John
xviii. 11.) It is love to my soul; God corrects with the same love that
he crowns me. God is now training me up for heaven; he carves me,
to make me a polished pillar, fit to stand in the heavenly mansion.
These sufferings bring forth patience, humility, even the peaceable
fruits of righteousness, Heb. xii. 11. And if God can bring such sweet
fruit out of a sour stock, let him graft me where he please. Thus
faith brings the heart to holy contentment.
2. Faith sucks the honey of contentment out of the hive of the
Promise.[A] Christ is the Vine, the promises are the clusters of
grapes that grow upon this Vine; and Faith presseth the sweet vine
of contentment out of these spiritual clusters of the promises. I will
show you but one cluster,—The Lord will give grace and glory, and
no good thing will he withhold from them that walk uprightly; (Psal.
lxxxiv. 11,) here is enough for faith to live upon. The Promise is the
flower out of which Faith distils the spirits and quintessence of divine
contentment. In a word, Faith carries up the soul, and makes it
aspire after more noble and generous delights than earth affords,
and to live in the world above the world. Would you lead contented
lives, live up to the height of your faith.

Breath after Assurance.


Oh, let us get the interest cleared between God and our own souls!
Interest is a word much in use; a pleasing word: interest in great
friends, interest-money. Oh, if there be an interest worth looking
after, it is an interest between God and the soul. Labor to say with
Thomas, my Lord and my God. To be without money and without
friends, and without God too, (Eph. ii. 12,) is said; but he whose
faith doth flourish into assurance, that can say, with St. Paul—I know
in whom I have believed, (2 Tim. i. 12.) Be assured that man hath
enough to give his heart contentment. When a man's debts are paid,
and he can go abroad without fear of arresting, what contentment is
this! Oh, let your title be cleared! if God be ours, whatever we want
in the creature is infinitely made up in him. Do I want bread? I have
Christ, the Bread of Life. Am I under defilement? His blood is like the
trees of the sanctuary; not only for meat, but medicine, Ezek. xlvii.
12. If any thing in the world is worth laboring for, it is to get sound
evidences that God is ours. If this be once cleared, what can come
amiss? No matter what storms I meet with, so that I know where to
put in for harbor. He that hath God to be his God, is so well
contented with his condition, that he doth not much care whether he
hath any thing else. To rest in a condition where a Christian cannot
say God is his God, is a matter of fear: and if he can say so truly,
and yet is not contented, is matter of shame. David encouraged
himself in the Lord his God. Although it was sad with him, (1 Sam.
xxx. 62.) Ziklag was burnt, his wives taken captive, he lost all, and
had like to have lost his soldiers' hearts too—for they spake of
stoning him—yet he had the ground of contentment within him, viz.,
an interest in God; and this was a pillar of supportment to his spirit.
He that knows God is his, and that all that is in God is for his good;
if this doth not satisfy, I know nothing will.

Pray for an Humble Spirit.


The humble man is the contented man: if his estate be low, his
heart is lower than his estate; therefore he is contented. If his
esteem is the world below, he that is little in his own eyes, will not
be much troubled to be little in the eyes of others. He hath a meaner
opinion of himself, than others can have of him. The humble man
studies his own unworthiness; he looks upon himself as less than the
least of God's mercies, (Gen. xxxii. 10,) and then a little will content
him. He cries out with Paul, that he is the chief of sinners, (1 Tim. i.
15,) therefore doth not murmur, but admire: he doth not say his
comforts are small, but his sins are great. He thinks it a mercy he is
out of hell; therefore, is contented. He doth not go to carve out a
more happy condition to himself; he knows the worst piece God cuts
him is better than he deserves. A proud man is never contented; he
is one that hath an high opinion of himself; therefore, under small
blessings is disdainful, under small crosses impatient. The humble
spirit is the contented spirit; if his cross be light, he reckons it in the
inventory of his mercies; if it be heavy, yet takes it upon his knees,
knowing that when his estate is bad, it is to make him the better.
Where you lay humility for the foundation, contentment will be the
superstructure, and Christ the topstone.

Keep a clear Conscience. 1 Tim. iii. 9.


Contentment is the manna that is laid up in the ark of a good
conscience. Oh, take heed of indulging any sin! It is as natural for
guilt to breed disquietude, as for the earth to breed worms. Sin lies
like Jonah in the ship, it raises a tempest. If dust or motes be gotten
into the eye, they make the eye water, and cause a soreness in it; if
the eye be clear, then it is free from that soreness. If sin be gotten
into the conscience, which is as the eye of the soul, then grief and
disquiet breed there: but keep the eye of conscience clear, and all is
well. What Solomon saith of a good stomach, I may say of a good
conscience (Prov. xxvii. 7.) To the hungry soul every bitter thing is
sweet; so to a good conscience every bitter thing is sweet; it can
pick contentment out of the Cross. A good conscience turns the
waters of Marah into wine. Would you have a quiet heart? Get a
smiling conscience. I wonder not to hear Paul say, he was in every
state content; when he could make that triumph—I have lived in all
good conscience unto this day, Acts, xxiii. 1. When once a man's
reckonings are clear, it must needs let in abundance of contentment
into the heart. A good conscience can suck contentment out of the
bitterest drug: under slanders—This is our rejoicing, the testimony of
our conscience, 2 Cor. i. 12. In case of imprisonment, Paul had his
prison-songs, and could play the sweet lesson of contentment when
his feet were in the stocks, Acts xvi. 24. Augustine calls it the
paradise of a good conscience. When the times are troublesome, a
good conscience makes a calm: if conscience be clear, what though
the days be cloudy?... Oh, keep conscience clear, and you shall
never want contentment!
THE HIDING PLACE.

Amid this world's tumultuous noise,


For peace my soul to Jesus flies;
If I've an interest in his grace,
I want no other hiding place.

The world with all its charms is vain,


Its wealth and honors I disdain;
All its extensive aims embrace,
Can ne'er afford a hiding place.

A guilty sinful heart is mine,


Jesus, unbounded love is thine!
When I behold thy smiling face,
Tis then I see my hiding place.

To save, if once my Lord engage,


The world may laugh, and Satan rage:
The powers of hell can ne'er erase
My name from God's own hiding place.

I'm in a wilderness below,


Lord, guide me all my journey through,
Plainly let me thy footsteps trace,
Which lead to heaven my hiding place.

Should dangers thick impede my course,


O let my soul sustain no loss;
Help me to run the Christian race,
And enter safe my hiding place.

Then with enlarged powers,


I'll triumph in redeeming love,
Eternal ages will I praise
My Lord for such a hiding place.
FOOTNOTE:
[A] 'Tis a comfortable thought that the promises of God are all given
for the express purpose that we may have great and strong
consolations, who make our duty and our privilege to be found
pleading them at the throne of grace;

O then be earnest, take no nay,


He'll answer every good desire;
Give him your hearts, though cold as clay,
They'll melt like wax before the fire.
*** END OF THE PROJECT GUTENBERG EBOOK A NARRATIVE OF
THE LIFE AND TRAVELS OF MRS. NANCY PRINCE ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like