1 / 50

A whole new class of programming

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 Pr2 Connect4Board Pr3 Connect4Player (extra credit, due Nov. 24, 2009).

zinna
Télécharger la présentation

A whole new class of programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 5 today A whole new classof 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 Pr2 Connect4Board Pr3 Connect4Player (extra credit, due Nov. 24, 2009) http://www.cs.hmc.edu/wiki/CS5/CS5GoldReviewExam2

  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 creating new data structures Invention, not reinvention.

  5. Lists, Tuples, Dictionaries, … + lots of functionality with very little programmer work

  6. 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., A[i] no options as to data organization… A = [ 42, 3.1, '!'] '!' 3.1 42 list str float int A A[2] A[0] A[1]

  7. 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., A[i] no options as to data organization… A = [ 42, 3.1, '!'] '!' 3.1 42 list str float int A A[2] A[0] A[1] Classes and Objects take care of all 3 drawbacks...

  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… Graphics libraries Python's class libraries… Do reference libraries have library references? http://docs.python.org/lib/

  11. 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 >>> z.conjugate() 3-4j a data member of all objects of class complex its value for this object, z a method (function) within all objects of class complex its return value for this object, z

  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. 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 ... ? ? z abs(z) == z.__abs__()

  14. Date This is a class. It is a user-defined datatype (that you'll build in Lab this week!) >>> d = Date(1,1,2008) >>> d 1/1/2008 this is a CONSTRUCTOR … What does it do? 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 12/31/2007 >>> d2.isLeapYear() False Another object of type Date - again, via the constructor. How does it know to return False, instead of True in this case ??

  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 defisLeapYear( self ): """ anyone know the rule? """ The Date class Why is everyone so far away?!

  16. is the specific OBJECT THAT CALLS A METHOD self >>> d = Date(1,1,2008) >>> d 1/1/2008 These methods need access to the object that calls them >>> d.isLeapYear() True Why not use d? >>> d2= Date(12,31,2007) >>> d2 12/31/2007 >>> d2.isLeapYear() False These methods need access to the object that calls them

  17. a Leap of faith…. class Date: def __init__( self, mo, dy, yr ): (constructor) def __repr__(self): (for printing) defisLeapYear( 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? d has changed! Some methods return a value; others change the object that call it!

  19. What date is on your id? What id is on your Date? Date ids >>> d = Date(11,26,2007) >>> d 11/26/2007 >>> d2 = Date(11,27,2007) >>> d2 11/27/2007 this initializes a different Date! >>> d ==d2 ? >>> d2.yesterday() >>> d ==d2 ?

  20. Double Date Excuse me -- ids please! >>> d2 = d >>> d 11/26/2007 >>> d.addNDays(36) >>> d2 ? >>> d2 = d.copy() >>> d2 == d ? >>> d.equals(d2) ? How many Dates are here?

  21. More Date class Date: def __init__( self, mo, dy, yr ): def __repr__(self): def isLeapYear(self): defcopy(self): """ returns a DIFFERENT object w/SAME date! """ defequals(self, d2): """ returns True if they represent the same date; False otherwise """ How many Dates are here? Would two be selfish?

  22. "Quiz" class Date: defisBefore(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 deftomorrow(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! + demo! Write this tomorrow method. It does not return anything. It just CHANGES the date object that calls it.

  23. What's wrong? class Date: defisBefore(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

  24. class Date: deftomorrow(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. Lab today / tomorrow Add to Date these methods no computer required… yesterday(self) tomorrow(self) addNDays(self, N) subNDays(self, N) isBefore(self, d2) isAfter(self, d2) diff(self, d2) dow(self) Prof. Art Benjamin and use your Date class to analyze our calendar a bit…

  26. Unusual calendar years…

  27. But Why ? • Flexibility create-your-own • Reusability write once, take anywhere • Abstraction worry once, use anywhere ordinary data structures

  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 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?

  30. Object-oriented programming Do-it-yourself data structures! Blueprint for an object class: your own TYPE of data object: a variable of your own class type real data What does a Date contain? data members: data an object contains How can you contain a function? methods: functions an object contains (!) Benefits: encapsulation & abstraction

  31. 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 String Course c name String list String CL the dot is used to get at parts of an object (data or actions) def addStudent(self, student)

  32. Accessing pieces of objects float hours String Course c name String list String the dot is used to get at parts of an object (data or actions) CL def addStudent(self, student) adds a student to the class

  33. int int NCOLS Connect Four: the objectb This is true for sufficiently broad definitions of “the creators of Python’s library” ... data members char char char char list NROWS data Board b char char char char char char char char def addMove(self, col, player) def allowsMove(self, col) def winsFor(self, player) methods

  34. 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?

  35. int int NCOLS Connect Four: the objectb This is true for sufficiently broad definitions of “the creators of Python’s library” ... data members char char char char list NROWS data Board b char char char char char char char char def addMove(self, col, player) What is player ? def allowsMove(self, col) def winsFor(self, player) methods

  36. int int NCOLS Connect Four: the objectb This is true for sufficiently broad definitions of “the creators of Python’s library” ... data members char char char char list NROWS data Board b char char char char char char char char def addMove(self, col, player) Which methods will alter b? Which leave it alone? def allowsMove(self, col) def winsFor(self, player) methods

  37. 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): onerow = [' ']*self.NCOLS self.data += [onerow] def __repr__(self): """ thoughts? """ look familiar? Starting code for the Board class

  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! Demo! (20).__add__(22) # yes, everything! x = 20 y = 22 x.__add__(y) # either way! id(x) Hey? Who are you? You mean superego? My ego approves!

  41. dir and help ! provide all of the methods and data members available to an object dir('any string') help(''.count) dir(42) dir( [] ) No memorizing! Just use dir & help… try sort!

  42. Object-oriented programming Do-it-yourself data structures! Blueprint for an object class: your own TYPE of data everything! object: a variable of your own class type What does a box contain? data members: data an object contains methods: functions an object contains (!) How can you contain a function? benefits: encapsulation & abstraction An object is alive, responsible, and intelligent. - C++ FAQs

More Related