Advanced Programming
Advanced Programming
Allan N
slide credit:
stanford.edu/~schmit/cme193
File I/O
Classes
Exercises
f = open(filename,
option)
option:
File I/O
Classes
Exercises
So far, we have seen many objects in the course that come standard
with Python.
Integers
Strings
Lists
Dictionaries
etc
So far, we have seen many objects in the course that come standard
with Python.
Integers
Strings
Lists
Dictionaries
etc
In languages such as C++ and Java: data protection with private and
public attributes and methods.
Don’t abuse power: works well in practice and leads to simple code.
# define class:
class Leaf:
pass
# instantiate
object leaf =
Leaf()
print leaf
# < main .Leaf instance at0x10049df80>
redleaf = Leaf(’red’)
blueleaf = Leaf(’blue’)
print redleaf.color
# red
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)
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)
class Leaf:
n_leafs = 0 # class attribute: shared
redleaf = Leaf(’red’)
blueleaf = Leaf(’blue’)
print redleaf.color
# red
print Leaf.n_leafs
# 2
Animal
Bird
Hawk
Seagull
...
Pet
Dog
Cat
...
...
class Animal:
def init (self, n_legs, color):
self.n_legs = n_legs
self.color = color
def make_noise(self):
print (’noise’)
class Dog(Animal):
def init (self, color, name):
Animal. init (self, 4, color)
self.name = name
def
make_noise(self):
print self.name + ’: ’ + ’woof’
init : Constructor
cmp : Compare
File I/O
Classes
Exercises
See course page on the e-learning site for exercises for this week. Let me
know if you have any question about exercises