Python 5
一. Review of Programs
1. Object Oriented Language
A program is made up of many cooperating objects.
Instead of being the "whole program" - each object is a little "island" within the program and cooperatively working with other objects.
A program is made up of one or more objects working together - objects make use of each other's capabilities.
(1) Object
An Object is a bit of self-contained Code and Data.
A key aspect of the Object approach is to break the problem into smaller understandable parts (divide and conquer).
Objects have boundaries that allow us to ignore un-needed detail.
We have been using objects all along : String Objects, Integer Objects, Dictionary Objects, List Objects......
class is a reserved word that tells the object to run the code. 如:
class PartyAnimal :(Party Animal就是object)
x = 0 (初始值)
def party (self) :(class里的一个function)
self. x = self. x + 1
print ("So far", self. x)
an = PartyAnimal() (执行语句,给PA定义了值为an)
an. party() (附带以上function,即run party() within the object an)
"self" is a formal argument that refers to the object itself.
"self. x" is saying "x within self"
"self" is "global within this object"
(2) Object Lifecycle
Objects are created, used and discarded.
We have special blocks of code (methods) that get called: At the moment of creation (constructor)(如上例的x) and At the moment of destruction (destructor)(指object被删除掉后).
Constructors are used a lot.
Destructors are seldom used.
Constructor - the primary purpose of the constructor is to set up some instance variables to have the proper initial values when the object is created.
The constructor and destructor are optional. The constructor is typically used to set up variables. The destructor is seldom used.
class 中的built-in function:
def __init__(self) : (相当于constructor的作用,也可以把初始值写到这个function下面),其作用是存储建立object的初始值
In object oriented programming, a constructor in a class is a special block of statements called when an object is created.
We can create lots of objects - the class is the template for the object.
We can store each distinct object in its own variable.
We call this having multiple instances of the same class.
Each instance has its own copy of the instance variables.
object中可以创建多个初始值,并用于之后的function中。 如:
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()
j = PartyAnimal("Jim")
j. party()
s. party()
Constructors can have additional parameters. These can be used to set up instance variables for the particular instance of the class (i.e., for the particular object).
Definitions:
Class - a template - Dog
Method or Message - A defined capability of a class - Bark()
Object or Instance - A particular instance of a class - Lassie
Constructor - A method which is called when the instance/object is created
二. Reading and Writing files
Reading files
1. Opening a File
Before we can read the contents of the file, we must tell Python which file we are going to work with and what we will be doing with the file.
This is done with the open() function which returns a "file handle"- a variable used to perform operations on the file.
Similar to "File->Open" in a Word Processor
2. Using open()
handle = open(filename, mode)
如 fhand = open ('mbox. txt', 'r')
returns a handle use to manipulate the file
filename is a string
mode is optional and should be 'r' if we are planning to read the file and 'w' if we are going to write to the file.
3. The newline Character代表上一个string结束,开始了新的string
We use a special character called the "newline" to indicate when a line ends.
We represent it as \n in strings.
Newline is still one character - not two.
4. File Handle as a Sequence
A file handle open for read can be treated as a sequence of strings where each line in the file is a string in the sequence.
We can use the for statement to iterate through a sequence.
Remember - a sequence is an ordered set.
如:xfile = open ('mbox. txt')
for cheese in xfile :
print (cheese)
5. Counting Lines in a File
Open a file read-only.
Use a for loop to read each line.
Count the lines and print out the number of lines.
如: fhand = open ('mbox. txt')
count = 0
for line in fhand :
count = count + 1
print ('Line Count:', count)
6. Reading the Whole File
We can read the whole file (newlines and all) into a single string.
如: fhand = open ('mbox-short. txt')
inp = fhand. read()
print (len (inp)) 94626
print (inp [:20]) From stephen.marquar
9. Searching Through a File
We can put an if statement in our for loop to only print lines that meet some criteria. 如:
fhand = open ('mbox-short. txt')
for line in fhand :
if line. startswith('From: ') :
print (line)
注: startswith() 是和string相关的一个function
OOPS!
What are all these blank lines doing here ?
Each line from the file has a newline(\n) at the end.
The print statement adds a newline to each line.
10. Searching Through a File (fixed)
We can strip the whitespace from the right-hand side of the string using rstrip() from the string library.(把找到的每行string后的\n去掉)
The newline is considered "whitespace" and is stripped. 如:
fhand = open ('mbox-short. txt')
for line in fhand :
line = line. rstrip ()
if line. startswith ('From: ') :
print (line)
11. Skipping with continue
We can conveniently skip a line by using the continue statement(显示结果同上例). 如:
fhand = open ('mbox-short. txt')
for line in fhand :
line = line. rstrip ()
if not line. startswith ('From: ') :
continue
print (line)
12. Using in to select lines
We can look for a string anywhere in a line as our selection criteria. 如:
fhand = open ('mbox-short. txt')
for line in fhand :
line = line. rstrip ()
if not '@uct.ac.za' in line :
continue
print (line)
Writing files
We could write to a file by using write function. 如:
fhand = open ('test. txt', 'w')
fhand. write ("Write some content here")
For example:
with open ('test_2. txt', 'r') as file1 :
with open ('output_2. txt', 'w') as file2 :
for line in file1 :
line = line. rstrip()
if line. startswith ('From: ') :
file2. write (line)
file2. write ('\n')
file1. close ()
file2. close ()