Text stringlengths 1 9.41k |
|---|
The rate-limiting approach allows
us to do simple, personal data retrievals but does not allow us to build a product
that pulls data from their API millions of times per day.
##### 13.9 Glossary
**API Application Program Interface - A contract between applications that defines**
the patterns of interaction between tw... |
A format that allows for the markup of struc-**
tured data based on the syntax of JavaScript Objects.
**SOA Service-Oriented Architecture. |
When an application is made of components**
connected across a network.
**XML eXtensible Markup Language.** A format that allows for the markup of
structured data.
-----
##### 13.10 Exercises
**Exercise** **1:** [Change either the www.pythonlearn.com/code3/geojson.py or](http://www.pythonlearn.com/code3/geojson.py... |
Add error checking so your program does not
traceback if the country code is not there. |
Once you have it working, search
for “Atlantic Ocean” and make sure it can handle locations that are not in any
country.
-----
## Chapter 14
# Object-Oriented Programming
##### 14.1 Managing Larger Programs
At the beginning of this book, we came up with four basic programming patterns
which we use to construct pr... |
There are many ways to write programs and by now, you
probably have written some programs that are “not so elegant” and other programs
that are “more elegant”. |
Even though your programs may be small, you are starting
to see how there is a bit of “art” and “aesthetic” to writing code.
As programs get to be millions of lines long, it becomes increasingly important to
write code that is easy to understand. |
If you are working on a million line program,
you can never keep the entire program in your mind at the same time. |
So we need
ways to break the program into multiple smaller pieces so to solve a problem, fix
a bug, or add a new feature we have less to look at.
In a way, object oriented programming is a way to arrange your code so that you
can zoom into 500 lines of the code, and understand it while ignoring the other
999,500 lines... |
So approach this chapter as a way to learn some terms and concepts and work through a few simple
examples to lay a foundation for future learning. |
Throughout the rest of the book
we will be using objects in many of the programs but we won’t be building our
own new objects in the programs.
The key outcome of this chapter is to have a basic understanding of how objects
are constructed and how they function and most importantly how we make use of
the capabilities o... |
Python provides
us with many built-in objects. |
Here is some simple code where the first few lines
should feel very simple and natural to you.
stuff = list()
stuff.append('python')
stuff.append('chuck')
stuff.sort()
print (stuff[0])
print (stuff.__getitem__(0))
print (list.__getitem__(stuff,0))
_# Code: http://www.pythonlearn.com/code3/party1.py_
But instead of ... |
Don’t worry
if the following paragraphs don’t make any sense the first time you read them
because we have not yet defined all these terms.
The first line is constructing an object of type list, the second and third lines are
calling the append() method, the fourth line is calling the sort() method, and the
fifth line ... |
Our elevator conversion program demonstrates a very short
but complete program showing all three of these steps.
usf = input('Enter the US Floor Number: ')
wf = int(usf) - 1
print('Non-US Floor Number is',wf)
_# Code: http://www.pythonlearn.com/code3/elev.py_
If we think a bit more about this program, there is the “... |
The input and output aspects are where the program interacts with the
outside world. |
Within the program we have code and data to accomplish the task
the program is designed to solve.
When we are “in” the program, we have some defined interactions with the “outside” world, but those interactions are well defined and generally not something
we focus on. |
While we are coding we worry only about the details “inside the
program”.
-----
###### Program
### Input Output
Figure 14.1: A Program
One way to think about object oriented programming is that we are separating
our program into multiple “zones”. |
Each “zone” contains some code and data (like
a program) and has well defined interactions with the outside world and the other
zones within the program.
If we look back at the link extraction application where we used the BeautifulSoup
library, we can see a program that is constructed by connecting different objects
... |
The urllib library uses the socket library to make the actual
network connection to retrieve the data. We take the string that we get back from
urllib and hand it to BeautifulSoup for parsing. |
BeautifulSoup makes use of
another object called html.parser[1] and returns an object. |
We call the tags()
method in the returned object and then get a dictionary of tag objects, and loop
through the tags and call the get() method for each tag to print out the ‘href’
attribute.
1https://docs.python.org/3/library/html.parser.html
-----
String Dictionary String
Input Object Object Object Output
Urllib ... |
It is also important to note that when
you looked at that program several chapters back, you could fully understand
what was going on in the program without even realizing that the program was
“orchestrating the movement of data between objects”. |
Back then it was just lines
of code that got the job done.
##### 14.5 Subdividing a Problem - Encapsulation
One of the advantages of the object oriented approach is that it can hide complexity.
For example, while we need to know how to use the urllib and BeautifulSoup
code, we do not need to know how those libraries ... |
It allows us to
focus on the part of the problem we need to solve and ignore the other parts of
the program.
|S Input O|tring bject|
|---|---|
|Urllib Object BeautifulSoup Object Socket html.parser Object Object||
Urllib Object BeautifulSoup
Object
Socket html.parser
Object Object
Figure 14.3: Ignoring Detail Wh... |
For example the
programmers developing BeautifulSoup do not need to know or care about how we
retrieve our HTML page, what parts we want to read or what we plan to do with
the data we extract from the web page.
Another word we use to capture this idea that we ignore the internal detail of
objects we use is “encapsulat... |
This means that we can know how to use an
-----
String Dictionary String
Input Object Object Object Output
Urllib Object BeautifulSoup
Object
Socket html.parser
Object Object
Figure 14.4: Ignoring Detail When Building an Object
object without knowing how it internally acomplishes what we need done.
##### 14.... |
Defining a function allows us to store a bit of code and give it a
name and then later invoke that code using the name of the function.
An object can contain a number of functions (which we call “methods”) as well as
data that is used by those functions. |
We call data items that are part of the object
“attributes”.
We use the class keyword to define the data and code that will make up each
of the objects. |
The class keyword includes the name of the class and begins an
indented block of code where we include the attributes (data) and methods (code).
**class PartyAnimal:**
x = 0
**def party(self) :**
self.x = self.x + 1
print("So far",self.x)
an = PartyAnimal()
an.party()
an.party()
an.party()
PartyAnimal.party(an)
_#... |
This example has one attribute (x) and one method
(party). |
The methods have a special first parameter that we name by convention
self.
Much like the def keyword does not cause function code to be executed, the
class keyword does not create an object. |
Instead, the class keyword defines a
-----
template indicating what data and code will be contained in each object of type
PartyAnimal. |
The class is like a cookie cutter and the objects created using the
class are the cookies[2]. |
You don’t put frosting on the cookie cutter, you put frosting
on the cookies - and you can put different frosting on each cookie.
Figure 14.5: A Class and Two Objects
If you continue through the example code, we see the first executable line of code:
an = PartyAnimal()
This is where we instruct Python to construct ... |
create) an object or “instance
of the class named PartyAnimal”. |
It looks like a function call to the class itself
and Python constructs the object with the right data and methods and returns
the object which is then assigned to the variable an. |
In a way this is quite similar
to the following line which we have been using all along:
counts = dict()
Here we are instructing Python to construct an object using the dict template
(already present in Python), return the instance of dictionary and assign it to the
variable counts.
When the PartyAnimal class is use... |
We use an to access the code and data for that particular
instance of a PartyAnimal object.
Each Partyanimal object/instance contains within it a variable x and a
method/function named party. |
We call that party method in this line:
an.party()
When the party method is called, the first parameter (which we call by convention
self) points to the particular instance of the PartyAnimal object that party is
called from within. |
Within the party method, we see the line:
2Cookie image copyright CC-BY https://www.flickr.com/photos/dinnerseries/23570475099
-----
self.x = self.x + 1
This syntax using the ‘dot’ operator is saying ‘the x within self’. |
So each time
party() is called, the internal x value is incremented by 1 and the value is printed
out.
To help make sense of the difference between a global function and a method within
a class/object, the following line is another way to call the party method within
the an object:
PartyAnimal.party(an)
In this vari... |
self within the method).
You can think of an.party() as shorthand for the above line.
When the program executes, it produces the following output:
So far 1
So far 2
So far 3
So far 4
The object is constructed, and the party method is called four times, both incrementing and printing the value for x within the an obj... |
And we can use the built-in
dir function to examine the capabilities of a variable. |
We can use type and dir
with the classes that we create.
**class PartyAnimal:**
x = 0
**def party(self) :**
self.x = self.x + 1
print("So far",self.x)
an = PartyAnimal()
print ("Type", type(an))
print ("Dir ", dir(an))
print ("Type", type(an.x))
print ("Type", type(an.party))
_# Code: http://www.pythonlearn.com/co... |
From the
dir output, you can see both the x integer attribute and the party method are
available in the object.
##### 14.8 Object Lifecycle
In the previous examples, we are defining a class (template) and using that class
to create an instance of that class (object) and then using the instance. |
When
the program finishes, all the varaibles are discarded. |
Usually we don’t think much
about the creation and destruction of variables, but often as our objects become
more complex, we need to take some action within the object to set things up as
the object is being constructed and possibly clean things up as the object is being
discarded.
If we want our object to be aware o... |
When Python
encounters the line:
an = 42
It actually ‘thows our object away’ so it can reuse the an variable to store the value
42. |
Just at the moment when our an object is being ‘destroyed’ our destructor
code (__del__) is called. |
We cannot stop our variable from being destroyed, but
we can do any necessary cleanup right before our object no longer exists.
When developing objects, it is quite common to add a constructor to an object to
set in intial values in the object, it is relatively rare to need to need a destructor
for an object.
##### 1... |
But the real power in object oriented happens
when we make many instances of our class.
When we are making multiple objects from our class, we might want to set up different initial values for each of the objects. |
We can pass data into the constructors
to give each object a different initial value:
**class PartyAnimal:**
x = 0
name = ''
**def __init__(self, nam):**
self.name = nam
print(self.name,'constructed')
**def party(self) :**
self.x = self.x + 1
print(self.name,'party count',self.x)
s = PartyAnimal('Sally')
s.party()... |
When extending a class, we call the
original class the ‘parent class’ and the new class as the ‘child class’.
For this example, we will move our PartyAnimal class into its own file:
**class PartyAnimal:**
x = 0
name = ''
**def __init__(self, nam):**
self.name = nam
print(self.name,'constructed')
**def party(self) :... |
This means that all of the variables (x) and methods
(party) from the PartyAnimal class are inherited by the CricketFan class.
You can see that within the six method in the CricketFan class, we can call the
party method from the PartyAnimal class. |
The variables and methods from the
parent class are merged into the child class.
As the program executes, we can see that the s and j are independent instances
of PartyAnimal and CricketFan. |
The j object has additional capabilities beyond
the s object.
Sally constructed
Sally party count 1
Jim constructed
Jim party count 1
Jim party count 2
Jim points 6
['__class__', '__delattr__', ... |
'__weakref__',
'name', 'party', 'points', 'six', 'x']
In the dir output for the j object (instance of the CricketFan class) you can
see that it both has the attributes and methods of the parent class as well as the
attributes and methods that were added when the class was extended to create the
CricketFan class.
####... |
Let’s quickly
review the code that we looked at in the beginning of the chapter. |
At this point
you should fully understand what is going on.
stuff = list()
stuff.append('python')
stuff.append('chuck')
stuff.sort()
print (stuff[0])
print (stuff.__getitem__(0))
-----
print (list.__getitem__(stuff,0))
_# Code: http://www.pythonlearn.com/code3/party1.py_
The first line constructs a list object. |
When Python creates the list object,
it calls the constructor method (named __init__) to set up the internal data
attributes that will be used to store the list data. |
Due to encapsulation we neither
need to know, nor need to care about these in internal data attributes are arranged.
We are not passing any parameters to the constructor and when the constructor
returns, we use the variable stuff to point to the returned instance of the list
class.
The second and third lines are call... |
And this is
equivalent to calling the __getitem__ method in the list class passing the stuff
object in as the first parameter and the position we are looking for as the second
parameter.
At the end of the program the stuff object is discarded but not before calling the
_destructor (named __del__) so the object can cle... |
There are
many additional details as to how to best use object oriented approaches when
developing large applications and libraries that are beyond the scope of this chapter.[3]
##### 14.12 Glossary
**attribute A variable that is part of a class.**
**class A template that can be used to construct an object. |
Defines the attrbutes**
and methods that will make up the object.
**child class A new class created when a parent class is extended. |
The child class**
inherits all of the attributes and methods of the parent class.
**constructor An optional specially named method (__init__) that is called at**
the moment when a class is being used to construct an object. |
Usually this
is used to set up initial values for the object.
3If you are curious about where the list class is defined, take a look at (hopefully the URL
won’t change) https://github.com/python/cpython/blob/master/Objects/listobject.c - the list
class is written in a language called “C”. |
If you take a look at that source code and find it curious
you might want to explore a few Computer Science courses.
-----
**destructor An optional specially named method (__del__) that is called at the**
moment just before an object is destroyed. |
Destructors are rarely used.
**inheritance When we create a new class (child) by extending an existing class**
(parent). |
The child class has all the attributes and methods of the parent
class plus additional asttributes and methods defined by the child class.
**method A function that is contained within a class and the objects that are con-**
structed from the class. |
Some object-oriented patterns use ‘message’ instead
of ‘method’ to describe this concept.
**object A constructed instance of a class. |
An object contains all of the attributes**
and methods that were defined by the class. |
Some object-oriented documentation uses the term ‘instance’ interchangably with ‘object’.
**parent class The class which is being extended to create a new chld class. |
The**
parent class contributes all of its methods and attributes to the new chaild
class.
-----
## Chapter 15
# Using databases and SQL
##### 15.1 What is a database?
A database is a file that is organized for storing data. |
Most databases are organized
like a dictionary in the sense that they map from keys to values. |
The biggest
difference is that the database is on disk (or other permanent storage), so it persists
after the program ends. |
Because a database is stored on permanent storage, it can
store far more data than a dictionary, which is limited to the size of the memory
in the computer.
Like a dictionary, database software is designed to keep the inserting and accessing
of data very fast, even for large amounts of data. |
Database software maintains its
performance by building indexes as data is added to the database to allow the
computer to jump quickly to a particular entry.
There are many different database systems which are used for a wide variety of purposes including: Oracle, MySQL, Microsoft SQL Server, PostgreSQL, and SQLite.
W... |
SQLite is designed to be embedded into other applications to provide database support within the application. |
For example, the Firefox
browser also uses the SQLite database internally as do many other products.
[http://sqlite.org/](http://sqlite.org/)
SQLite is well suited to some of the data manipulation problems that we see
in Informatics such as the Twitter spidering application that we describe in this
chapter.
##### 15... |
When you want to do one or very few operations on a text file, you can just
open it in a text editor and make the changes you want. |
When you have many
changes that you need to do to a text file, often you will write a simple Python
program. You will find the same pattern when working with databases. |
You will
do simple operations in the database manager and more complex operations will
be most conveniently done in Python.
##### 15.4 Creating a database table
Databases require more defined structure than Python lists or dictionaries[1].
When we create a database table we must tell the database in advance the name... |
When the database software knows the type of data in each
column, it can choose the most efficient way to store and look up the data based
on the type of data.
You can look at the various data types supported by SQLite at the following url:
[http://www.sqlite.org/datatypes.html](http://www.sqlite.org/datatypes.html)
... |
If the file does not exist, it will be created.
The reason this is called a “connection” is that sometimes the database is stored
on a separate “database server” from the server on which we are running our
application. |
In our simple examples the database will just be a local file in the
same directory as the Python code we are running.
A cursor is like a file handle that we can use to perform operations on the data
stored in the database. |
Calling cursor() is very similar conceptually to calling
open() when dealing with text files.
|execute| U S - |Col3|
|---|---|---|
|fetchone|||
|fetchall|||
|close|||
|execute U fetchone S fetchall - close Your Program|Users Courses Members|
|---|---|
Users Courses
Members
Figure 15.2: A Database Curso... |
The database language is called Structured Query Language or SQL for
short.
[http://en.wikipedia.org/wiki/SQL](http://en.wikipedia.org/wiki/SQL)
In our example, we are executing two SQL commands in our database. |
As a
convention, we will show the SQL keywords in uppercase and the parts of the
-----
command that we are adding (such as the table and column names) will be shown
in lowercase.
The first SQL command removes the Tracks table from the database if it exists.
This pattern is simply to allow us to run the same program... |
Note that the DROP TABLE
command deletes the table and all of its contents from the database (i.e., there is
no “undo”).
cur.execute('DROP TABLE IF EXISTS Tracks ')
The second command creates a table named Tracks with a text column named
title and an integer column named plays.
cur.execute('CREATE TABLE Tracks (titl... |
Again, we begin by making a connection
to the database and obtaining the cursor. |
We can then execute SQL commands
using the cursor.
The SQL INSERT command indicates which table we are using and then defines a
new row by listing the fields we want to include (title, plays) followed by the
VALUES we want placed in the new row. |
We specify the values as question marks
(?, ?) to indicate that the actual values are passed in as a tuple ( ’My Way’,
15 ) as the second parameter to the execute() call.
import sqlite3
conn = sqlite3.connect('music.sqlite')
cur = conn.cursor()
cur.execute('INSERT INTO Tracks (title, plays) VALUES (?, ?)',
('Thunder... |
On the SELECT command, we indicate which columns we would like (title,
plays) and indicate which table we want to retrieve the data from. |
After we
execute the SELECT statement, the cursor is something we can loop through in a
for statement. |
For efficiency, the cursor does not read all of the data from the
database when we execute the SELECT statement. |
Instead, the data is read on
demand as we loop through the rows in the for statement.
The output of the program is as follows:
Tracks:
('Thunderstruck', 20)
('My Way', 15)
Our for loop finds two rows, and each row is a Python tuple with the first value
as the title and the second value as the number of plays.
_Note... |
This_
_was an indication in Python 2 that the strings are Unicode* strings that are capable_
of storing non-Latin character sets. |
In Python 3, all strings are unicode strings by
default.*
At the very end of the program, we execute an SQL command to DELETE the
rows we have just created so we can run the program over and over. |
The DELETE
command shows the use of a WHERE clause that allows us to express a selection
criterion so that we can ask the database to apply the command to only the rows
that match the criterion. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.