Programming & Numerical Analysis: Kai-Feng Chen
Programming & Numerical Analysis: Kai-Feng Chen
PROGRAMMING &
NUMERICAL ANALYSIS2014
Lecture 05:
I/O, exceptions and class
using the print statement. You are already doing that all the time!
>>> print 'Hello World!'
Hello World!
used with two arguments: filename and mode. The close() method
of a file object flushes any unwritten information and closes the file
object:
r : opens a file for reading only. This is the default file access
mode.
w : opens a file for writing only; overwrites the file if the file
exists.
a : opens a file for appending. If the file does not exist, it creates
a new file for writing.
One can also add a b (e.g. rb, wb) to open a file for reading/
writing in binary format.
For example:
fin = open('foo.txt')
str = fin.read()
print 'foo.txt: ',str
fin.close()
This is the output:
foo.txt: Imagination is more important than
knowledge.
---Albert Einstein
7
fin = open('foo.txt')
for l in fin:
print 'line:',l
fin.close()
line: Imagination is more important than knowledge.\n
come with l
\n
add by print statement
line: ---Albert Einstein\n
\n
You may notice the new line character (\n) is in the content of
each line which has been read in.
9
SEEKING THROUGH
A FILE
The tell() method tells you the current position within the file.
The seek() method changes the current position within the file.
>>> fin = open('foo.txt')
>>> fin.read(30)
'Imagination is more important '
>>> fin.tell()
30
>>> fin.seek(10, 0)
move to position 10, starting from beginning
>>> fin.read(30)
'n is more important than knowl'
>>> fin.seek(-30, 1)
move to position -30, starting from current place
>>> fin.read(30)
'n is more important than knowl'
The second parameter of seek() can be
0 (beginning of file), 1 (current position), or 2 (end of file).
11
INTERMISSION
We only tried to write a string into the file. How could we store a
complex object like a list? e.g.
12
INTERMISSION (II)
You may find that you can finally get a file (foo.txt) with the
following content:
iambuggy.py
>>> open('a_file_does_not_exist.txt')
IOError: [Errno 2] No such file or directory
>>> open('/etc/passwd', 'w')
IOError: [Errno 13] Permission denied
>>> open('/usr/bin')
IOError: [Errno 21] Is a directory
Whenever you try to do something invalid, your program will
stop immediately. Although this is not a critical issue (at least you
will know what is wrong), but it makes your program
not-so-professional.
15
CATCHING EXCEPTIONS
To avoid these errors, one can go ahead and try first and deal
with problems if they happen with a special routine which is
exactly what the try statement does.
try:
fin = open('bad_file')
for line in fin:
print line
fin.close()
except:
print 'Something went wrong.'
In this case, your program does not stop with the
exception and continue to the except block.
16
try:
print 'Do something here...'
# access to file, do some calculations, etc.
except IOError:
print 'There much be an input/output error!'
except ValueError:
print 'The value must be wrong!'
else:
print 'Everything fine, move ahead!'
The list of standard exceptions can be found by
>>> import exceptions
>>> help(exceptions)
18
RAISING AN EXCEPTION
You can even raise an exception and send the code to run the
Surely if you put the raise within the try statement, the code will
jump to your predefined exception block.
19
INTERMISSION
What will happen if the code generate an exception which is not in
the exception block list, e.g.:
try:
x = y = 1
z = (x+y)/(x-y)
except IOError:
print 'There much be an input/output error!'
else:
print 'Everything is fine!'
20
ATTRIBUTES
In the example point class, it has two default attributes of x,y.
Values can be assigned to an instance using the dot notation:
>>> p.x = 2.0
>>> p.x, p.y
(2.0, 0.0)
The assigned values are only valid within the assigned instance:
>>> q = Point()
>>> q.x, q.y
(0.0, 0.0)
23
ATTRIBUTES (II)
Unlike C/C++, the Python class attributes can be actually added
on-the-fly to the specific instance. One can start with an empty
class and insert your data and form a structure-like object:
>>> class placeholder:
...
pass
...
>>> obj = placeholder()
>>> obj.pi = 3.14159
>>> obj.list = [1,2,3]
>>> obj.str = 'hello world!'
>>> print obj.pi,obj.list,obj.str
3.14159 [1, 2, 3] hello world!
24
INSTANTIATION
Many classes like to create objects with instances customized to a
25
METHODS
Usually a method (object) can be defined under the class block:
class Point(object):
def rho(self):
return (self.x**2+self.y**2)**0.5
A method can be called right after it is bound:
>>> p = Point(3.,4.)
>>> p.rho()
5.0
The first argument of a method is called self. The attributes
stored in the instance can be accessed through it.
26
BASE METHODS
OVERRIDING
You can always override some of the default base (magic)
27
BASE METHODS
OVERRIDING (II)
So if you define the class like this:
class Point(object):
'Example point class for 2D space.'
def __init__(self, x=0., y=0.):
self.x,self.y = x,y
def rho(self):
return (self.x**2+self.y**2)**0.5
def __str__(self):
return '(x=%g,y=%g)' % (self.x,self.y)
def __cmp__(self,other):
return cmp(self.rho(),other.rho())
just compare the
distance toward origin.
def __add__(self,other):
return Point(self.x+other.x, self.y+other.y)
def __mul__(self,other):
return self.x*other.x+self.y*other.y
28
BASE METHODS
OVERRIDING (III)
Lets try it out:
>>> p = Point(1.,2.)
>>> q = Point(2.,3.)
>>> print 'p = '+str(p)+', q = '+str(q)
p = (x=1,y=2), q = (x=2,y=3)
>>> print 'Is p closer to the origin than q?',p<q
Is p closer to the origin than q? True
>>> str(p+q)
'(x=3,y=5)'
Surely you can add more and more magic
>>> p*q
methods to the class, and it will become very
8.0
much similar to a regular built-in python type.
More information: http://www.rafekettler.com/magicmethods.html
29
ALIASING AND
COPYING
Remember if you assign b = a, where a is a list. Both variables refer
to the same object (aliasing):
>>> a = [1,2,3]
>>> b = a
>>> a is b
True
a
b
[1,2,3]
a
b
30
Point()
ALIASING AND
COPYING (II)
Aliasing can make a program difficult to read because changes in
a
b
Point()
Point()
ALIASING AND
COPYING (III)
However, there could be such a case an object (such as list) is an
attribute of your class. The copy.copy() function will not copy the
underneath object but a reference. This is called a shallow copy.
>>> import copy
>>> class mydata:
...
def __init__(self,save):
...
self.data = save
...
>>> a = mydata([1,2,3])
>>> b = copy.copy(a)
>>> b is a
although b is not an alias of a
False
>>> b.data is a.data
but b.data is still a reference of a.data
True
32
ALIASING AND
COPYING (IV)
The solution is the deep copy with the copy.deepcopy() function. It
copies not only the object but also the objects it refers to, and the
objects they refer to, and so on.
>>> a = mydata([1,2,3])
>>> c = copy.deepcopy(a)
>>> c is a
False
>>> c.data is a.data
now c.data is a full copy of a.data, not
False
a reference anymore.
Remark: the copy module works well with regular type like list!
33
CLASS INHERITANCE
Instead of starting from scratch, you can create a class by deriving
The child class inherits the attributes of its parent class, and you
can use those attributes as if they were defined in the child class. A
child class can also override data members and methods from the
parent.
class Point(object):
'Example point class for 2D space.'
In the previous example, object is the base (parent) class.
Class object is the most base type in Python.
34
INTERMISSION
Try to observe how many base (magic) methods have to be
overwritten for a full-functioning type. You can try this to see how
a Python complex number class working:
>>> help(complex)
The copy module works with built-in object as well. Try to make a
copy of a list of list, and see if sub-lists are real copies or just a
reference.
>>> l = [[1,2,3],[4,5,6]]
36
HANDS-ON SESSION
Practice 1 (a):
37
HANDS-ON SESSION
Practice 1 (b):
Instead of raw_input(), read the data back from the file and parse the
file line-by-line. Store those information back and store them as a list
of list, e.g.
[['last name', 'Chen'], ['first name', 'KaiFeng'], ['phone number', '33665153'],
['address', 'R529, Department of Physics,
NTU']]
38
HOMEWORK #5
Exercise: