CS 5 Lecture 18 - HMC Computer Science

Download Report

Transcript CS 5 Lecture 18 - HMC Computer Science

CS 5 today
A whole new class of programming
HW10: Due Sun, Nov 15
Pr0: Ariane 5 Reading
Exam 2 on M/T (but no Lab!)
Digital Logic, HMMM, Loops,
Dictionaries, Mutation
Pr1/Lab: the Date class
http://www.cs.hmc.edu/wiki/CS5/CS5GoldReviewExam2
Pr2
Connect4Board
Pr3
Connect4Player
(extra credit, due Nov. 24, 2009)
Software Engineering
Building atop the
work of others…
Insight into details, e.g.,
data storage and retrieval.
Invention, not reinvention.
creating and
composing
functions
Software Engineering
Building atop the
work of others…
creating and
composing
functions
Insight into details, e.g.,
data storage and retrieval.
loops and
data handling
Invention, not reinvention.
Software Engineering
Building atop the
work of others…
creating and
composing
functions
Insight into details, e.g.,
data storage and retrieval.
loops and
data handling
Invention, not reinvention.
creating new
data structures
Lists, Tuples, Dictionaries, …
+
lots of functionality with very little programmer work
Lists, Tuples, Dictionaries, …
+
lots of functionality with very little programmer work
fairly generic capabilities, e.g., len, print
-
limited to square-bracket naming, e.g.,
no options as to data organization…
42
list
A
int
A[0]
3.1
float
A[1]
A[i]
A = [ 42, 3.1, '!']
'!'
str
A[2]
Lists, Tuples, Dictionaries, …
+
lots of functionality with very little programmer work
fairly generic capabilities, e.g., len, print
-
limited to square-bracket naming, e.g.,
no options as to data organization…
42
list
A
int
A[0]
3.1
float
A[1]
A[i]
A = [ 42, 3.1, '!']
'!'
str
A[2]
Classes and Objects take care of all 3 drawbacks...
Classes & Objects
An object-oriented programming language allows you
to build your own customized types of variables.
(1) A class is a type of variable.
(2) An object is one such variable.
Classes & Objects
An object-oriented programming language allows you
to build your own customized types of variables.
(1) A class is a type of variable.
(2) An object is one such variable.
There will typically
be MANY objects
of a single class.
Examples…
Graphics libraries
Python's class libraries…
Do reference
libraries have
library
references?
http://docs.python.org/lib/
Using objects and classes:
A particularly complex example…
>>> z = 3 + 4j
>>> dir(z)
all of the data members and methods of the complex class (and thus the object z !)
>>> z.imag
4.0
its value for
this object, z
>>> z.conjugate()
3-4j
its return value
for this object, z
a data member of all objects
of class complex
a method (function) within
all objects of class complex
Objects
An object is a data structure (like a list), except
(1) Its data elements have names chosen by the programmer.
(2) Data elements are chosen & organized by the programmer
(3) An object can have behaviors built-in by the programmer.
usually called "methods"
instead of functions
objective Advantages:
a Python complex number
my complex number
real = 3.0
imag = 4.0
...
def __abs__():
return sqrt(self.real**2
+ self.imag**2)
...
r = 5.0
theta = 0.927
...
def __abs__():
return r
?
abs(z)
...
z
==
?
z.__abs__()
Date
This is a class. It is a user-defined datatype
(that you'll build in Lab this week!)
>>> d = Date(1,1,2008)
this is a CONSTRUCTOR …
What does
it do?
>>> d
1/1/2008
this is an object of type Date
the representation of a particular object of type Date
>>> d.isLeapYear()
True
the isLeapYear method returns
True or False. How does it know
what year to check?
>>> d2 = Date(12,31,2007)
>>> d2
Another object of type Date again, via the constructor.
12/31/2007
>>> d2.isLeapYear()
False
How does it know to return False,
instead of True in this case ??
class Date:
""" a blueprint (class) for objects
that represent calendar days
"""
def __init__( self, mo, dy, yr ):
""" the Date constructor """
self.month = mo
self.day = dy
self.year = yr
def __repr__( self ):
""" used for printing Dates """
s = "%02d/%02d/%04d" % (self.month,
return s
def isLeapYear( self ):
""" anyone know the rule? """
The Date
class
self.day, self.year)
Why is everyone
so far away?!
self
is the specific OBJECT THAT
CALLS A METHOD
>>> d = Date(1,1,2008)
>>> d
1/1/2008
>>> d.isLeapYear()
True
>>> d2 = Date(12,31,2007)
>>> d2
12/31/2007
>>> d2.isLeapYear()
False
These methods need
access to the object
that calls them
Why not use d?
These methods need
access to the object
that calls them
a Leap of faith….
class Date:
def __init__( self, mo, dy, yr ): (constructor)
def __repr__(self): (for printing)
John Herschel
def isLeapYear( self ):
""" here it is """
if self.yr%400 == 0: return True
if self.yr%100 == 0: return False
if self.yr%4 == 0: return True
return False
How about a
4000-year rule?
Date
>>> d = Date(1,1,2008)
always created with the
CONSTRUCTOR …
>>> d
1/1/2008
>>> d.yesterday()
>>> d
the yesterday method returns
nothing at all. Is it doing anything?
d has changed!
12/31/2007
>>> d.addNDays(35)
lots of printing…
>>> d
Some methods return a value; others
change the object that call it!
Date ids
>>> d = Date(11,26,2007)
>>> d
11/26/2007
>>> d2 = Date(11,27,2007)
>>> d2
11/27/2007
>>> d == d2
?
>>> d2.yesterday()
>>> d == d2
?
What date is on your id?
What id is on your Date?
this initializes a different Date!
Excuse me -ids please!
Double Date
>>> d2 = d
>>> d
11/26/2007
>>> d.addNDays(36)
>>> d2
?
>>> d2 = d.copy()
>>> d2 == d
?
>>> d.equals(d2)
?
How many Dates
are here?
class Date:
More Date
def __init__( self, mo, dy, yr ):
def __repr__(self):
def isLeapYear(self):
def copy(self):
""" returns a DIFFERENT object w/SAME date! """
def equals(self, d2):
""" returns True if they represent
the same date; False otherwise
"""
How many Dates
are here?
Would two be
selfish?
class Date:
This method is WRONG! Find why …
and suggest how you could fix it!
def isBefore(self, d2):
""" if self is before d2, this should
return True; else False """
if self.year < d2.year: return True
if self.month < d2.month: return True
if self.day < d2.day: return True
return False
def tomorrow(self):
""" moves the date that calls it ahead 1 day,
*not* accounting for leap years """
DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31]
"Quiz"
+ demo!
Write this
tomorrow method.
It does not return anything.
It just CHANGES the date
object that calls it.
class Date:
What's wrong?
def isBefore(self, d2):
""" if self is before d2, this should
return True; else False """
if self.year < d2.year: return True
if self.month < d2.month: return True
if self.day < d2.day: return True
return False
class Date:
def tomorrow(self):
""" moves the date that calls it ahead 1 day,
*not* accounting for leap years """
DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31]
Lab today / tomorrow
Add to Date these methods
yesterday(self)
tomorrow(self)
addNDays(self, N)
subNDays(self, N)
isBefore(self, d2)
isAfter(self, d2)
diff(self, d2)
dow(self)
no computer required…
Prof. Art Benjamin
and use your Date class to
analyze our calendar a bit…
Unusual calendar years…
But Why ?
• Flexibility
create-your-own
• Reusability
write once, take anywhere
• Abstraction
worry once, use anywhere
ordinary data structures
Connect Four
For your convenience, the creators of Python’s library have included
a Board class that can represent any size of Connect Four board... !
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |X| | | |
| |X| |X|O| | |
|X|O|O|O|X| |O|
--------------0 1 2 3 4 5 6
Connect Four
For your convenience, the creators of Python’s library have included
a Board class that can represent any size of Connect Four board... !
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | |X| | | |
| |X| |X|O| | |
|X|O|O|O|X| |O|
--------------0 1 2 3 4 5 6
Suppose our Board class's 2d list of
lists is named self.data. What is
the name of this single spot?
Object-oriented programming
Do-it-yourself data structures!
Blueprint for
an object
real data
class: your own TYPE of data
object: a variable of your own class type
What does a
data members: data an object contains
Date contain?
How can you
contain a
function?
methods: functions an object contains (!)
Benefits: encapsulation & abstraction
Objects
An object is a data structure (like a list), except
(1) Its data elements have names chosen by the programmer.
(2) Data elements are chosen & organized by the programmer
(3) An object can have behaviors built-in by the programmer.
float
hours
Course
c
String
name
list
CL
the dot is used to get at
parts of an object
(data or actions)
String
String
def addStudent(self, student)
Accessing pieces of objects
float
hours
Course
c
the dot is used to get at
parts of an object
(data or actions)
String
name
list
CL
String
String
def addStudent(self, student)
adds a student to the class
Connect Four: the object b
This is true for sufficiently broad definitions of “the creators of Python’s library” ...
data members
int
NROWS
Board
b
int
NCOLS
list
data
char
char
char
char
char
char
char
char
char
char
char
char
def addMove(self, col, player)
def allowsMove(self, col)
def winsFor(self, player)
methods
Sets values between low and hi to 0.0.
def zerospan( L, hi, low ):
newL = []
for x in L:
if low <= x <= hi:
newL += [0.0]
else:
newL += [x]
L = newL
Does this change L?
Connect Four: the object b
This is true for sufficiently broad definitions of “the creators of Python’s library” ...
data members
int
NROWS
Board
b
What is
player ?
int
NCOLS
list
data
char
char
char
char
char
char
char
char
char
char
char
char
def addMove(self, col, player)
def allowsMove(self, col)
def winsFor(self, player)
methods
Connect Four: the object b
This is true for sufficiently broad definitions of “the creators of Python’s library” ...
data members
int
NROWS
Board
b
Which methods will
alter b? Which
leave it alone?
int
NCOLS
list
data
char
char
char
char
char
char
char
char
char
char
char
char
def addMove(self, col, player)
def allowsMove(self, col)
def winsFor(self, player)
methods
Connect Four: Board
class Board:
def __init__( self, numRows, numCols ):
""" our Board's constructor """
self.NROWS = numRows
self.NCOLS = numCols
self.data = []
for r in range(self.NROWS):
look familiar?
onerow = [' ']*self.NCOLS
self.data += [onerow]
def __repr__(self):
""" thoughts? """
Starting code for the Board class
Connect Four: Board
class Board:
def __init__( self, numRows, numCols ):
""" our Board's constructor """
self.NROWS = numRows
self.NCOLS = numCols
self.data = []
for r in range(self.NR):
look familiar?
onerow = [' ']*self.NC
self.data += [onerow]
def __repr__(self):
""" thoughts? """
s = '\n'
for r in range(self.NROWS):
s += '|'
for c in range(self.NCOLS):
s += self.data[r][c] + '|'
a bit more to go !
return s
Everything in python is an object!
Demo!
s = 'harvey mudd college'
s.spit()
What the L?
s.__len__()
# Huh?
s.title()
# another entitlement?
20*'spam'.title()
# how many capital S's?
('spam'*20).title()
# bound to be good!
Yes, everything!
Demo!
(20).__add__(22)
# yes, everything!
x = 20
y = 22
x.__add__(y)
# either way!
Hey? Who
are you?
My ego
approves!
You mean
superego?
id(x)
dir and help !
provide all of the methods and data
members available to an object
dir('any string')
help(''.count)
dir(42)
No memorizing! Just
use dir & help…
dir( [] )
try sort!
Object-oriented programming
Do-it-yourself data structures!
class: your own TYPE of data
Blueprint for
an object
object: a variable of your own class type
everything!
data members: data an object contains
What does a
box contain?
methods: functions an object contains (!)
benefits: encapsulation & abstraction
An object is alive,
responsible, and intelligent.
- C++ FAQs
How can you
contain a
function?