CS 505: Advanced Programming
Lecture 4: File IO, Classes
Allan N
slide credit:
stanford.edu/~schmit/cme193
4: File IO, Classes 4-1
Contents
File I/O
Classes
Exercises
4: File IO, Classes 4-2
File I/O
How to read from and write to disk.
4: File IO, Classes 4-3
The file object
Interaction with the file system is pretty straightforward in Python.
Done using file objects
We can instantiate a file object using open or
file
4: File IO, Classes 4-4
Opening a file
f = open(filename,
option)
filename: path and filename
option:
’r’ read file
’w’ write to file
’a’ append to file
We need to close a file after we are done:
f.close()
4: File IO, Classes 4-5
with open() as f
Very useful way to open, read/write and close file:
with open(’data/text_file.txt’, ’r’) as
f:
print f.read()
4: File IO, Classes 4-6
Reading files
read() Read entire line (or first n characters, if supplied)
readline() Reads a single line per call
readlines() Returns a list with lines (splits at newline)
Another fast option to read a file
with open(’f.txt’, ’r’) as f:
for line in f:
print line
4: File IO, Classes 4-7
Reading files
read() Read entire line (or first n characters, if supplied)
readline() Reads a single line per call
readlines() Returns a list with lines (splits at newline)
Another fast option to read a file
with open(’f.txt’, ’r’) as f:
for line in f:
print line
4: File IO, Classes 4-8
Writing to file
Use write() to write to a
file
with open(filename, ’w’) as f:
f.write("Hello,{}!\n".format(name))
4: File IO, Classes 4-9
Contents
File I/O
Classes
Exercises
4: File IO, Classes 4-11
Defining our own objects
So far, we have seen many objects in the course that come standard
with Python.
Integers
Strings
Lists
Dictionaries
etc
But often one wants to build (much) more complicated structures.
4: File IO, Classes 4-12
Defining our own objects
So far, we have seen many objects in the course that come standard
with Python.
Integers
Strings
Lists
Dictionaries
etc
But often one wants to build (much) more complicated structures.
4: File IO, Classes 4-13
Object Oriented Programming
Express computation in terms of objects, which are instances of classes
Class Blueprint (only one)
Object Instance (many)
Classes specify attributes (data) and methods to interact with the
attributes.
4: File IO, Classes 4-15
Object Oriented Programming
Express computation in terms of objects, which are instances of classes
Class Blueprint (only one)
Object Instance (many)
Classes specify attributes (data) and methods to interact with the
attributes.
4: File IO, Classes 4-16
Python’s way
In languages such as C++ and Java: data protection with private and
public attributes and methods.
Not in Python: only basics such as inheritance.
Don’t abuse power: works well in practice and leads to simple code.
4: File IO, Classes 4-17
Simplest example
# define class:
class Leaf:
pass
# instantiate
object leaf =
Leaf()
print leaf
# < main .Leaf instance at0x10049df80>
4: File IO, Classes 4-18
Initializing an object
Define how a class is instantiated by defining the init method.
Seasoned programmer: in Python only one constructor method.
4: File IO, Classes 4-19
Initializing an object
The init or constructor method.
class Leaf:
def init (self, color):
self.color = color # private
attribute
redleaf = Leaf(’red’)
blueleaf = Leaf(’blue’)
print redleaf.color
# red
Note how we access object attributes.
4: File IO, Classes 4-20
Self
The self parameter seems strange at first sight.
It refers to the the object (instance) itself.
Hence self.color = color sets the color of the object
self.color
equal to the variable color.
4: File IO, Classes 4-21
Another example
Classes have methods (similar to functions)
class Stock():
def init (self, name, symbol, prices=[]):
self.name = name
self.symbol = symbol
self.prices = prices
def high_price(self):
if len(self.prices) == 0:
return ’MISSINGPRICES’
return max(self.prices)
apple = Stock(’Apple’, ’APPL’, [500.43,570.60])
print apple.high_price()
Recall: list.append() or dict.items(). These are simply class methods!
4: File IO, Classes 4-22
Another example
Classes have methods (similar to functions)
class Stock():
def init (self, name, symbol, prices=[]):
self.name = name
self.symbol = symbol
self.prices = prices
def high_price(self):
if len(self.prices) == 0:
return ’MISSING
PRICES’
return max(self.prices)
apple = Stock(’Apple’, ’APPL’, [500.43,570.60])
print apple.high_price()
Recall: list.append() or dict.items(). These are simply class methods!
4: File IO, Classes 4-23
Class attributes
class Leaf:
n_leafs = 0 # class attribute: shared
def init (self, color):
self.color = color # object
attribute
Leaf.n_leafs += 1
redleaf = Leaf(’red’)
blueleaf = Leaf(’blue’)
print redleaf.color
# red
print Leaf.n_leafs
# 2
Class attributes are shared among all objects of that class.
4: File IO, Classes 4-24
Class hierarchy through inheritance
It can be useful (especially in larger projects) to have a hierarchy of
classes.
Example
Animal
Bird
Hawk
Seagull
...
Pet
Dog
Cat
...
...
4: File IO, Classes 4-25
Inheritance
Suppose we first define an abstract class
class Animal:
def init (self, n_legs, color):
self.n_legs = n_legs
self.color = color
def make_noise(self):
print (’noise’)
4: File IO, Classes 4-26
Inheritance
We can define sub classes and inherit from another class.
class Dog(Animal):
def init (self, color, name):
Animal. init (self, 4, color)
self.name = name
def
make_noise(self):
print self.name + ’: ’ + ’woof’
bird = Animal(2, ’white’)
bird.make_noise()
# noise
brutus = Dog(’black’, ’Brutus’)
brutus.make_noise()
# Brutus: woof
shelly = Dog(’white’, ’Shelly’)
shelly.make_noise()
# Shelly: woof
4: File IO, Classes 4-27
Base methods
Some methods to override
init : Constructor
repr : Represent the object (machine)
str : Represent the object (human)
cmp : Compare
4: File IO, Classes 4-28
Contents
File I/O
Classes
Exercises
4: File IO, Classes 4-42
Exercises
See course page on the e-learning site for exercises for this week. Let me
know if you have any question about exercises
4: File IO, Classes 4-43