CME 193: Introduction to Scientific Python
Lecture 4: File I/O and Classes
Sven Schmit
stanford.edu/~schmit/cme193
4: File I/O and Classes 4-1
Feedback form
Please take a moment to fill out feedback form
http://goo.gl/forms/NBkBXWgnCC
Note: link also on couse website.
4: File I/O and Classes 4-2
Contents
File I/O
Classes
Exercises
4: File I/O and Classes 4-3
File I/O
How to read from and write to disk.
4: File I/O and Classes 4-4
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 I/O and Classes 4-5
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 I/O and Classes 4-6
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 I/O and 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 I/O and Classes 4-8
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 I/O and Classes 4-9
Writing to file
Use write() to write to a file
with open(filename, ’w’) as f:
f.write("Hello, {}!\n".format(name))
4: File I/O and Classes 4-10
More writing examples
# write elements of list to file
with open(filename, ’w’) as f:
for x in xs:
f.write(’{}\n’.format(x))
# write elements of dictionary to file
with open(filename, ’w’) as f:
for k, v in d.iteritems():
f.write(’{}: {}\n’.format(k, v))
4: File I/O and Classes 4-11
Contents
File I/O
Classes
Exercises
4: File I/O and 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 I/O and Classes 4-13
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 I/O and Classes 4-14
Hangman example
Objects:
Game
Agents (different versions)
4: File I/O and 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 I/O and Classes 4-16
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 I/O and Classes 4-17
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 I/O and Classes 4-18
Simplest example
# define class:
class Leaf:
pass
# instantiate object
leaf = Leaf()
print leaf
# <__main__.Leaf instance at 0x10049df80>
4: File I/O and Classes 4-19
Initializing an object
Define how a class is instantiated by defining the __init__ method.
Seasoned programmer: in Python only one constructor method.
4: File I/O and Classes 4-20
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 I/O and Classes 4-21
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 I/O and 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 I/O and Classes 4-23
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 I/O and Classes 4-24
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 I/O and Classes 4-25
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 I/O and Classes 4-26
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 I/O and Classes 4-27
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 I/O and Classes 4-28
Base methods
Some methods to override
__init__: Constructor
__repr__: Represent the object (machine)
__str__: Represent the object (human)
__cmp__: Compare
4: File I/O and Classes 4-29
Example
Implementing Rational numbers
class Rational:
pass
4: File I/O and Classes 4-30
Setup
What information should the class hold?
Numerator
Denominator
4: File I/O and Classes 4-31
Setup
What information should the class hold?
Numerator
Denominator
4: File I/O and Classes 4-32
Init
Implement the __init__ method
class Rational:
def __init__(self, p, q=1):
self.p = p
self.q = q
4: File I/O and Classes 4-33
Init
Implement the __init__ method
class Rational:
def __init__(self, p, q=1):
self.p = p
self.q = q
4: File I/O and Classes 4-34
Issues
Issues?
class Rational:
def __init__(self, p, q=1):
self.p = p
self.q = q
Ignore the division by 0 for now, more on that later.
4: File I/O and Classes 4-35
Issues
Issues?
class Rational:
def __init__(self, p, q=1):
self.p = p
self.q = q
Ignore the division by 0 for now, more on that later.
4: File I/O and Classes 4-36
Greatest common divisor
10 1
20 and 2 are the same rational.
Implement a gcd(a, b) function that computes the greatest common
divisor of a and b.
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
Exercise: Verify Euclidean Algorithm
4: File I/O and Classes 4-37
Greatest common divisor
class Rational:
def __init__(self, p, q=1):
g = gcd(p, q)
self.p = p / g
self.q = q / g
Why is this awesome?
4: File I/O and Classes 4-38
Representing your class: Operator overloading
Implement __repr__ or __str__ early to print
Debugging
4: File I/O and Classes 4-39
Operator overloading: adding two Rationals
Add Rationals just like Ints and Doubles?
Rational(10,2) + Rational(4,3)
To use +, we implement the __add__ method
class Rational:
# ...
def __add__(self, other):
p = self.p * other.q + other.p * self.q
q = self.q * other.q
return Rational(p, q)
# ...
4: File I/O and Classes 4-40
Operator overloading: Comparing
__cmp__ compares objects
If self is smaller than other, return a negative value
If self and other are equal, return 0
If self is larger than other, return a positive value
4: File I/O and Classes 4-41
More on Operator Overloading
To learn more:
Google ‘Python operator overloading’.
4: File I/O and Classes 4-42
Contents
File I/O
Classes
Exercises
4: File I/O and Classes 4-43
Exercises
See course website for exercises for this week.
Get to know the person next to you and do them in pairs!
Let me know if you have any question
Class ends at 5:35pm.
4: File I/O and Classes 4-44