Python 3 Object Oriented Programming 1st Edition Dusty Phillips - Download the full ebook set with all chapters in PDF format
Python 3 Object Oriented Programming 1st Edition Dusty Phillips - Download the full ebook set with all chapters in PDF format
https://ebookfinal.com/download/beginning-c-object-oriented-
programming-1st-edition-dan-clark/
https://ebookfinal.com/download/object-oriented-programming-with-
smalltalk-1st-edition-harald-wertz/
https://ebookfinal.com/download/beginning-c-object-oriented-
programming-2nd-edition-dan-clark/
https://ebookfinal.com/download/object-oriented-programming-and-java-
second-edition-danny-poo/
Object Oriented Programming using Java 1st edition Edition
Kendal S.
https://ebookfinal.com/download/object-oriented-programming-using-
java-1st-edition-edition-kendal-s/
https://ebookfinal.com/download/object-oriented-programming-in-vb-
net-1st-edition-alistair-mcmonnies/
https://ebookfinal.com/download/beginning-object-oriented-programming-
with-c-1st-edition-jack-purdum/
https://ebookfinal.com/download/real-time-c-efficient-object-oriented-
and-template-microcontroller-programming-2nd-edition-unknown/
https://ebookfinal.com/download/object-oriented-reengineering-
patterns-1st-edition-serge-demeyer/
Python 3 Object Oriented Programming 1st Edition
Dusty Phillips Digital Instant Download
Author(s): Dusty Phillips
ISBN(s): 9781847197900, 1849510660
Edition: 1
File Details: PDF, 5.88 MB
Year: 2010
Language: english
Python 3 Object Oriented
Programming
Dusty Phillips
BIRMINGHAM - MUMBAI
Python 3 Object Oriented Programming
Copyright © 2010 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book
is sold without warranty, either express or implied. Neither the author nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
ISBN 978-1-849511-26-1
www.packtpub.com
Proofreader
Acquisition Editor
Chris Smith
Steven Wilding
Graphics
Development Editor
Geetanjali Sawant
Mayuri Kokate
Production Coordinator
Technical Editor
Shantanu Zagade
Vanjeet D'souza
Cover Work
Indexer
Shantanu Zagade
Hemangini Bari
About the Author
Jason Chu is the CTO and part founder of Oprius Software Inc. He's developed
software professionally for over 8 years. Chu started using Python in 2003 with
version 2.2. When not developing personal or professional software, he spends his
time teaching karate, playing go, and having fun in his hometown: Victoria, BC,
Canada. You'll often find him out drinking the Back Hand of God Stout at Christie's
Carriage House.
Michael Driscoll has been programming Python for almost 4 years and has
dabbled in other languages since the late nineties. He graduated from university
with a Bachelor's degree in Science, majoring in Management Information Systems.
Michael enjoys programming for fun and profit. His hobbies include biblical
apologetics, blogging about Python at http://www.blog.pythonlibrary.org/,
and learning photography. Michael currently works for the local government
where he programs with Python as much as possible. This is his first book as a
technical reviewer.
[ iii ]
Table of Contents
[ iv ]
Table of Contents
[]
Preface
This book will introduce you to the terminology of the object-oriented paradigm,
focusing on object-oriented design with step-by-step examples. It will take you from
simple inheritance, one of the most useful tools in the object-oriented programmer's
toolbox, all the way through to cooperative inheritance, one of the most complicated.
You will be able to raise, handle, define, and manipulate exceptions.
Chapter 2, Objects in Python discusses classes and objects and how they are used in
Python. We will learn about attributes and behaviors in Python objects, and also the
organization of classes into packages and modules. And lastly we shall see how to
protect our data.
Chapter 3, When Objects are Alike gives us a more in-depth look into inheritance. It
covers multiple inheritance and shows us how to inherit from built-ins. This chapter
also covers polymorphism and duck typing.
Preface
Chapter 4, Expecting the Unexpected looks into exceptions and exception handling. We
shall learn how to create our own exceptions. It also deals with the use of exceptions
for program flow control.
Chapter 5, When to Use Object-oriented Programming deals with objects; when to create
and use them. We will see how to wrap data using properties, and restricting data
access. This chapter also discusses the DRY principle and how not to repeat code.
Chapter 7, Python Object-oriented Shortcuts as the name suggests, deals with little
time-savers in Python. We shall look at many useful built-in functions, then move
on to using comprehensions in lists, sets, and dictionaries. We will learn about
generators, method overloading, and default arguments. We shall also see how
to use functions as objects.
Chapter 9, Python Design Patterns II picks up where the previous chapter left us. We
shall see the adapter pattern, facade pattern, flyweight pattern, command pattern,
abstract pattern, and composite pattern with suitable examples in Python.
Chapter 10, Files and Strings looks at strings and string formatting. Bytes and byte
arrays are also discussed. We shall also look at files, and how to write and read data
to and from files. We shall look at ways to store and pickle objects, and finally the
chapter discusses serializing objects.
Chapter 11, Testing Object-oriented Programs opens with the use of testing and why
testing is so important. It focuses on test-driven development. We shall see how to
use the unittest module, and also the py.test automated testing suite. Lastly we
shall cover code coverage using coverage.py.
Chapter 12, Common Python 3 Libraries concentrates on libraries and their utilization
in application building. We shall build databases using SQLAlchemy, and user
interfaces TkInter and PyQt. The chapter goes on to discuss how to construct XML
documents and we shall see how to use ElementTree and lxml. Lastly we will use
CherryPy and Jinja to create a web application.
[]
Preface
If you are an object-oriented programmer for other languages you will also find
this book a useful introduction to Python, as it uses terminology you are already
familiar with.
Python 2 programmers seeking a leg up in the new world of Python 3 will also find
the book beneficial but you need not necessarily know Python 2.
Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text are shown as follows: "We can access other Python modules
through the use of the import statement."
[]
Preface
When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
class Friend(Contact):
def __init__(self, name, email, phone):
self.name = name
self.email = email
self.phone = phone
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "We use
this feature to update the label to a new random value every time we click the
Roll! button".
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.
[]
Preface
If there is a book that you need and would like to see us publish, please
send us a note in the SUGGEST A TITLE form on www.packtpub.com or
e-mail suggest@packtpub.com.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you get the most from your purchase.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text
or the code—we would be grateful if you would report this to us. By doing so, you
can save other readers from frustration and help us improve subsequent versions
of this book. If you find any errata, please report them by visiting http://www.
packtpub.com/support, selecting your book, clicking on the let us know link, and
entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list
of existing errata, under the Errata section of that title. Any existing errata can be
viewed by selecting your title from http://www.packtpub.com/support.
[]
Preface
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
We appreciate your help in protecting our authors, and our ability to bring you
valuable content.
Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.
[]
Object-oriented Design
In software development, design is often considered the step done before
programming. This isn't true; in reality, analysis, programming, and design
tend to overlap, combine, and interweave. In this chapter, we will learn:
Object-oriented?
Everyone knows what an object is: a tangible "something" that we can sense, feel, and
manipulate. The earliest objects we interact with are typically baby toys. Wooden
blocks, plastic shapes, and over-sized puzzle pieces are common first objects. Babies
learn quickly that certain objects do certain things. Triangles fit in triangle-shaped
holes. Bells ring, buttons press, and levers pull.
Proceed to Teheran—Takhtrowan—Duties—Gulhaek—Lawn-tennis—Guebre
gardener—A good road—The Shah—Custom of the Kūrūk—M. Gersteiger—
Cossack regiments—Austrian officers—New coinage—Count Monteforte—
New police—Boulevard des Ambassadeurs—English Embassy—Tile gates—
Summer palaces—Bazaars—Russian goods—Demarvend—Drive to Ispahan
—Difficulties of the journey—Accidents—Danger of sunstroke—Turkeys—
Keeping peacocks—Armenian tribute of poultry—Burmese and Japanese
embassies—Entertainment and fireworks—Cruel treatment of Jews—Oil
paintings—Bahram and his queen—Practice makes perfect—Pharaoh and the
Red Sea—Pharaoh and the magicians.
The Russian goods are liked in the Eastern market. They are very
cheap, and very strong; in fact, are suited to the country; they are
also, alas! very ugly. The tremendous land journey from Trebizonde,
or that from the Persian Gulf, or the alternative from Baghdad viâ
Kermanshah, closes the Persian market at Teheran to the English.
Fortunes, however, are made there, an importer of French goods
(which are particularly appreciated by the Persians) having retired
with a large one. About four hundred per cent. is generally charged,
which covers the heavy freight and the duty, and leaves about cent.
per cent. profit.
We found a great deal of gaiety at Teheran. A weekly dinner at the
Embassy, generally a daily drive, and the society of many Europeans
of different nationalities, was of course a great break in the
monotony of our life in Persia. But our pleasures after four months
were interrupted by the serious illness of my wife. Our second little
boy was born, and we were lucky in having a reliable nurse.
The view of Teheran is made very unique by the great semi-extinct
volcano, Demarvend, in the distance, which gives it great grandeur,
towering, as it does, over the valley, with its top covered in eternal
snows, and taking innumerable lovely tints at the rising and setting of
the sun.
We came to Teheran by the longer way of Natanz, thus avoiding
the great Kohrūd pass, a particularly unpleasant stage when there is
much snow; and as my wife was really an invalid, we determined to
return to Ispahan driving—a thing no one has done before, and I
fancy no one will do again. I had a new set of wheels made specially
strong and heavy, and with very strong tyres. I succeeded in buying
a second pair of half-broken horses, in case my own pair came to
grief, and we left in the autumn for Ispahan, the nurse and babies
occupying the takhtrowan, while my wife and I went in the trap.
We drove through the town with some trouble, and as soon as we
were clear of the fortifications the road became broad and level, and
we reached Hadjiabad, a garden, where we stopped the night.
The next day we crossed a rocky mountain, having to drag the
phaeton by hand some miles, and then, locking the wheels with
ropes, we got it down a very steep place. The rest was plain sailing;
the roads were generally fairly good. My wife had to get out only
some four times on a fifteen days’ journey, and it was only on getting
into or out of villages, where there were at times deep ditches, but
plenty of willing helpers, that we had any difficulty.
On our last stage but three we mistook the road, and came forty-
eight miles instead of twenty-four. We, however, only used our
second pair once, as they were very unsafe; and our horses, strange
to say, did the whole journey well, and arrived in fair condition.
At the last stage but two a ridiculous accident occurred. We had
frequently snapped the heads of bolts, and even the bolts
themselves, by going over very rough places, the jolt breaking the
heads off, as they were steel. These we generally detected and
replaced by others, which we had caused to be made in Teheran.
But Mūrchicah is a big village, with numerous twists and turns
between dead walls ere one gets to the post-house. We had come a
long stage, were very tired, and very anxious to get in, and, instead
of going over a deep dry ditch which we had to pass, and which was
very narrow, in a careful way, I was foolish enough to try to pass it
quickly. The result was a snap of all three bolts that fixed the trap to
what is, I fancy, technically termed the fore-carriage. The thing hung
together till we had got the hind wheels out of the ditch, and then the
horses, pole, and two front wheels went on, the carriage itself
remaining behind and falling forward; and, had not the apron been
up, we should have been shot out. Fortunately the reins were long,
and the horses easily pulled up. They were probably unaware of the
accident. Though we were in the village there was no one about. The
servants were either in front with the bedding, or behind with the
loads, yet in five minutes the bolts were replaced by fresh ones, and
we were proceeding on our way.
At this stage our little boy was taken very ill, and we both felt that
another march in the sun in the “kajawehs,” with his man-nurse,
might be fatal to him. So next morning we started very early, and
taking him in the trap, which had a hood and an opening with a cut
leather curtain behind, that made it very cool: we hurried over the
twenty-two miles, and did it in two hours and twenty minutes through
deep sand.
The next day’s stage was a very bad one, as, though short, we
had to pass through the town, and had to take the horses out twice,
and I dreaded our own very narrow and dangerous road to the
house. However, we got in without accident, by starting at dawn,
before ten; and the child, by rest and nursing, was soon himself
again.
The sun in Persia is a very insidious enemy. Many cases of sun-
apoplexy each year are seen, and I had a fixed rule that, except for
evening rides, my wife and I always wore an Elwood’s sun-helmet,
and this is the only real way to preserve oneself. All other things but
the topi are valueless, unless one uses the hideous pith hat, or
resorts to the turban. Of course in India these precautions are still
more necessary. I don’t know if these sun hats are made for children.
They are very necessary if children are allowed to go at all in the
sun, and they will go, and natives will let them. But really good-
looking riding-hats are turned out for ladies. My wife had a solar
riding-hat à la Gainsborough, that was almost becoming; so that
ladies at least have no excuse. I was constantly warning those under
my care of the danger of little caps, billycocks, etc., but in many
cases I was looked on as a “Molly,” though I felt it my duty to press
my warnings. Of another thing I am convinced, that the powerful
effect of the sun is much lost sight of in Europe, and I look on a
bright helmet of metal, unless air-chambered, as an invention of the
devil, and pity the poor Life Guards, etc.; the horsehair, however,
happily saves them a little.
On our journey down, at a place called Sinsin, we saw a big
turkey, and succeeded in buying a pair for fifty kerans, supposing
them to be the only pair. We found afterwards that the head-man of
the neighbouring village had a hundred birds, and the price
afterwards fell to eight shillings a bird.
We were very successful in the rearing of the young turkeys, the
hens sitting on their own eggs, and proving good mothers. So many
poults did we have, that, when we left Ispahan eighteen months
afterwards, we ate two a week for nearly six months. The turkeys
were of two varieties, the ordinary black ones, as seen in Europe,
and of large size, and a smaller bird, of lighter colour, and more
delicate, some of which latter were almost pure white.
Peacocks are much valued in Persia, and supposed only to be
kept by royalty: the English Minister has several fine birds, and the
privilege of keeping them is jealously guarded.
We brought a quantity of tame ducks down from Teheran; these
increased and multiplied amazingly, and bred with some wild ducks
of the common kind. We brought also three geese. Geese, ducks,
and turkeys were common long ago in Julfa when Ispahan was the
capital, but the Armenians, finding that they had to pay a yearly
tribute of fat birds, allowed them to die out, and so escaped the
exaction. However, when we left Julfa, all the Europeans had turkeys
and ducks, and there were plenty of geese at Soh, three stages off:
so, doubtless, by now (two years) they are plentiful.
We were glad to get back to our own home, for though Teheran
gave us most of the joys of civilisation, still we felt that our home was
in our big house at Julfa. And how we did enjoy not having to start as
usual the next morning!
Our stay in Ispahan was not chequered by any very exciting
events, save those personal to ourselves.
During our sojourn, two ambassadors passed through it. One, the
Burmese, an old and cheery man with huge ears, accompanied by a
staff of attachés, one of whom spoke English well, and had been
educated at King’s College. He was supposed to be carrying rubies
for disposal through Europe. He had a ring with him as a present
from the King of Burmah to the Shah. Hoop, collet, and all, were cut
out of one solid and perfect ruby of the first water—a truly barbarous
present. These Burmese all wore the national apology for
unmentionables—a handsome sheet of silk, termed a “langouti.” This
is wrapped around the waist, and depends nearly to the feet; their
heads were bound with fillets of muslin. The Zil-es-Sultan gave an
entertainment in their honour, to which we were all invited. A fair
dinner was followed by fireworks; these in Persia are always fairly
good, the only thing being that Persians do not understand coloured
fireworks, otherwise their displays are very good. One very good
feature is, that the public are always freely admitted. All the walls are
marked out with clay oil-lamps, and festoons of the same hang from
wires affixed to high poles: these are lighted after sunset, as soon as
it is dark. Music of a promiscuous character is played, all the
musicians and singers joining in to different airs. The military bands
strike up, each man playing his loudest at his own sweet will. A gun
is fired, and the huge golden rains from earthen cones light up the
whole scene, disclosing the shouting throng of good-tempered
Persians of the lower orders; all people of condition having been
provided with rooms and seats. All the roofs are thronged with
crowds of veiled women, flights of rockets are continually let off, and
the set-pieces soon commence. These are supplied in great
profusion, and, save for the want of colour, they are quite equal to
any effort of European pyrotechny.
A row of wretched Jews are now pushed into the tank—a
proceeding which always accompanies any official display of
fireworks. I know not why, unless it is to let the poor Jews feel, even
in times of rejoicing, the wretchedness of their position. Dancing
boys dressed as girls twirl and tumble, buffoons dance and pose
grotesquely, the noise of music and singing is at its loudest.
“Kūrbāghah” (frogs), a kind of water firework, are thrown in the tanks
in every direction, and, as the set-pieces are fading, the whole
concludes with a tremendous bouquet of fire as in Europe.
The Japanese ambassador, or rather commissioner, was received
with less ceremony, as he was proceeding incog. on his way to
Europe, having a mission to introduce Japanese goods to the notice
of Europeans generally. His attachés, too, spoke French and
English, and were funny little fellows; but, as the Persians put it, “too
ugly to have any value, even as slaves!”
We patronised art in Ispahan by having oil-paintings, executed by
native artists, of incidents in Persian life; some of these were
sufficiently curious. Among the subjects illustrated were “The Sticks,”
a very tragic picture indeed, where the expressions of pain, terror,
supplication, and ferocity were well shown.
Another amusing series were five pictures representing the history
of Bahram and his queen. The monarch is shown as pinning, with a
master-shot from his bow, the foot of an antelope to its side while it
was scratching itself.
“What do you think of that?” says the exulting king.
“Oh, practice makes perfect,” coolly remarked the lady.
They naturally separate; for it is a dangerous thing for a wife to
disparage her husband’s shooting. And here a curious parody of an
ancient classical legend occurs. Bahram hears of a lady of great
strength, who is in the habit of carrying a full-sized bull to the top of a
tower!
He goes to see the prodigy, and sees a lovely woman perform the
feat (scene depicted); his astonishment is manifested by his placing
his finger to his mouth—the typical gesture for this sensation in
Eastern art.
“Oh, that is nothing,” says the triumphant queen, “practice makes
perfect.” She then explains that she had commenced her feat when
the bull was a little calf. The king smiled, and took her back.
Many of the subjects illustrated were the histories from the Koran.
Thus the passage of the Egyptians, and their subsequent fate in the
Red Sea, is shown; Pharaoh and his host drowning, while a green-
winged angel exhibits to the sinking monarch a divine scroll, on
which his sentence is written. The expiring Egyptians are good, and
the look of horror on the face of Pharaoh is well done. But a small
steamer is seen in the distance! Another picture was “The staff of
Aaron changed to a serpent, having devoured the serpents of the
magicians of Egypt.” Here the winged dragon (or serpent) of Aaron is
so tremendous, that Wagner would have been glad of him at
Bayreuth: he is vomiting fire, and is a bogey of the first water.
Pharaoh, his eyes starting from his head, is depicted in horror, while
Moses has the satisfied expression of a conjurer after a successful
tour de force. Another represents Iskender (Alexander the Great),
who, having conquered the world, proceeds to the regions of eternal
night, as according to Persian legend he did in fact. The conqueror
and his warriors are well and carefully drawn, many of the figures
carrying torches and cressets; but the eternal night is shown by
painting the whole of the figures, trees, etc., on a black ground, and
a curious effect is thus produced.
Solomon in all his glory (see Frontispiece) is a favourite subject.
Solomon, who had the power of speaking the languages of animals
and all created things, and who could command the spirits of the
earth and air, is seen seated on his throne. Above his head is the
fabulous bird, the simūrgh; to his right, on a perch, is his favourite
the hoopöe, below this are two tiny efreet. The Queen of Sheba is
seated in a chair of state, behind her are her female servants and
slaves, and two gigantic jinns (genii). To the king’s left, are his Vizier
Asaph (the author of the Psalms of Asaph, or possibly the person to
whom they were dedicated), and Rūstam, the Persian Hercules,
armed with his bull-headed mace. Behind them are four jinns of
terrible aspect. The air is full of birds; and the foreground of beasts,
reptiles, and insects. The tiny figures with crowns are angels,
servants of Solomon; the turbaned figures are courtiers and
servants.
CHAPTER XXXV.
WE RETURN VIÂ THE CASPIAN.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com