Download presentation
Presentation is loading. Please wait.
Published byEsther Heath Modified over 9 years ago
1
A whole new class of programming CS 5 today HW10: Due Sun, Nov 15 Pr0: Ariane 5 Reading Pr1/Lab:the Date class Pr2 Connect4Board Pr3 Connect4Player (extra credit, due Nov. 24, 2009) Exam 2 on M/T (but no Lab!) http://www.cs.hmc.edu/wiki/CS5/CS5GoldReviewExam2 Digital Logic, HMMM, Loops, Dictionaries, Mutation
2
Software Engineering creating and composing functions Building atop the work of others… Insight into details, e.g., data storage and retrieval. Invention, not reinvention.
3
Software Engineering creating and composing functions Building atop the work of others… Insight into details, e.g., data storage and retrieval. loops and data handling Invention, not reinvention.
4
Software Engineering creating and composing functions Building atop the work of others… Insight into details, e.g., data storage and retrieval. loops and data handling Invention, not reinvention. creating new data structures
5
Lists, Tuples, Dictionaries, … + lots of functionality with very little programmer work
6
Lists, Tuples, Dictionaries, … + - lots of functionality with very little programmer work no options as to data organization… limited to square-bracket naming, e.g., fairly generic capabilities, e.g., len, print A[i] list int float str A A[0]A[1] A[2] A = [ 42, 3.1, '!'] 42 3.1 '!'
7
Lists, Tuples, Dictionaries, … + - lots of functionality with very little programmer work no options as to data organization… limited to square-bracket naming, e.g., fairly generic capabilities, e.g., len, print A[i] Classes and Objects take care of all 3 drawbacks... list int float str A A[0]A[1] A[2] A = [ 42, 3.1, '!'] 42 3.1 '!'
8
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.
9
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.
10
Examples… Do reference libraries have library references? Python's class libraries… Graphics libraries http://docs.python.org/lib/
11
Using objects and classes: >>> 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 >>> z.conjugate() 3-4j A particularly complex example… a data member of all objects of class complex its value for this object, z its return value for this object, z a method (function) within all objects of class complex
12
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
13
object ive Advantages: abs(z) == z.__abs__() 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... my complex numbera Python complex number z ??
14
Date this is an object of type Date >>> d = Date(1,1,2008) >>> d 1/1/2008 This is a class. It is a user-defined datatype (that you'll build in Lab this week!) this is a CONSTRUCTOR … What does it do? the repr esentation of a particular object of type Date >>> d.isLeapYear() True >>> d2 = Date(12,31,2007) >>> d2 12/31/2007 >>> d2.isLeapYear() False the isLeapYear method returns True or False. How does it know what year to check? How does it know to return False, instead of True in this case ?? Another object of type Date - again, via the constructor.
15
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, self.day, self.year) return s def isLeapYear( self ): """ anyone know the rule? """ The Date class Why is everyone so far away?!
16
>>> d = Date(1,1,2008) >>> d 1/1/2008 self These methods need access to the object that calls them >>> d.isLeapYear() True >>> d2 = Date(12,31,2007) >>> d2 12/31/2007 >>> d2.isLeapYear() False is the specific OBJECT THAT CALLS A METHOD These methods need access to the object that calls them Why not use d ?
17
a Leap of faith…. class Date: def __init__( self, mo, dy, yr ): (constructor) def __repr__(self): (for printing) 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 John Herschel How about a 4000-year rule?
18
Date >>> d = Date(1,1,2008) >>> d 1/1/2008 always created with the CONSTRUCTOR … >>> d.yesterday() >>> d 12/31/2007 >>> d.addNDays(35) lots of printing… >>> d the yesterday method returns nothing at all. Is it doing anything? Some methods return a value; others change the object that call it! d has changed!
19
Date id s >>> d = Date(11,26,2007) >>> d 11/26/2007 >>> d2 = Date(11,27,2007) >>> d2 11/27/2007 this initializes a different Date! What date is on your id ? What id is on your Date? >>> d == d2 ? >>> d2.yesterday() >>> d == d2 ?
20
Double Date >>> d2 = d >>> d 11/26/2007 >>> d.addNDays(36) >>> d2 ? >>> d2 = d.copy() >>> d2 == d ? >>> d.equals(d2) ? Excuse me -- id s please! How many Dates are here?
21
class 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 """ More Date How many Dates are here? Would two be self ish?
22
"Quiz" + demo! class Date: 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] This method is WRONG! Find why … and suggest how you could fix it! Write this tomorrow method. It does not return anything. It just CHANGES the date object that calls it.
23
class Date: 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 What's wrong?
24
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]
25
Add to Date these methods no computer required… Prof. Art Benjamin Lab today / tomorrow yesterday(self) tomorrow(self) addNDays(self, N) subNDays(self, N) isBefore(self, d2) isAfter(self, d2) diff(self, d2) dow(self) and use your Date class to analyze our calendar a bit…
26
Unusual calendar years…
27
But Why ? Flexibility Reusability Abstraction ordinary data structures create-your-own write once, take anywhere worry once, use anywhere
28
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
29
Connect Four | | | | | | | |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? For your convenience, the creators of Python’s library have included a Board class that can represent any size of Connect Four board... !
30
class: your own TYPE of data object: a variable of your own class type data members: data an object contains methods: functions an object contains (!) Benefits: encapsulation & abstraction Blueprint for an object real data What does a Date contain? How can you contain a function? Do-it-yourself data structures! Object-oriented programming
31
Course c def addStudent(self, student) String list float name CL hours String 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. the dot is used to get at parts of an object (data or actions)
32
Course c def addStudent(self, student) String list float name CL hours String Accessing pieces of objects the dot is used to get at parts of an object (data or actions) adds a student to the class
33
Connect Four: the object b This is true for sufficiently broad definitions of “the creators of Python’s library”... Board b def addMove(self, col, player) int NROWS int NCOLS def allowsMove(self, col) char data list char def winsFor(self, player) data members methods
34
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? Sets values between low and hi to 0.0.
35
Connect Four: the object b This is true for sufficiently broad definitions of “the creators of Python’s library”... Board b def addMove(self, col, player) int NROWS int NCOLS def allowsMove(self, col) char data list char def winsFor(self, player) data members methods What is player ?
36
Connect Four: the object b This is true for sufficiently broad definitions of “the creators of Python’s library”... Board b def addMove(self, col, player) int NROWS int NCOLS def allowsMove(self, col) char data list char def winsFor(self, player) data members methods Which methods will alter b ? Which leave it alone?
37
Connect Four: Board Starting code for the Board class 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): onerow = [' ']*self.NCOLS self.data += [onerow] def __repr__(self): """ thoughts? """ look familiar?
38
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): 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] + '|' return s look familiar? a bit more to go !
39
Everything in python is an object! Demo! s = 'harvey mudd college' s.spit() s.__len__() # Huh? s.title() # another entitlement? 20*'spam'.title() # how many capital S's? ('spam'*20).title() # bound to be good! What the L?
40
Yes, everything! (20).__add__(22) # yes, everything! x = 20 y = 22 x.__add__(y) # either way! id(x) Demo! My ego approves! You mean superego? Hey? Who are you?
41
dir and help ! provide all of the methods and data members available to an object No memorizing! Just use dir & help… dir('any string') help(''.count) dir(42) dir( [] ) try sort!
50
Do-it-yourself data structures! class: your own TYPE of data object: a variable of your own class type data members: data an object contains methods: functions an object contains (!) benefits: encapsulation & abstraction Object-oriented programming Blueprint for an object everything! What does a box contain? How can you contain a function? An object is alive, responsible, and intelligent. - C++ FAQs
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.