EECS 110 Lec 14 Classes and Objects Aleksandar
EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University http: //networks. cs. northwestern. edu/EECS 110 -s 18/
“Quiz” Change this code so that it keeps track of how many times you've guessed each item. • first, for real provinces • then, for incorrect guesses… def province. Challenge( prov ): while 0 in prov. values(): guess = input("Guess: ") if guess not in prov: print('Try again. . . ’) elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed. . . ') def fav. Child( person, Tree ): if person in Tree: Kids = Tree[person] Kids. sort() return Kids[0] else: return 'no children' Based on fav. Child, write fav. GChild to return the first grandchild alphabetically - or return 'no one' if there are none. def fav. GChild( person, Tree ):
Change this code so that it tells you how many times you've guessed the same province… • first, for real provinces • then, for incorrect guesses… def province. Challenge( prov ): while 0 in prov. values(): guess = input("Guess: ") if guess not in prov: print('Try again. . . ’) elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed. . . ‘)
Change this code so that it tells you how many times you've guessed the same province… • first, for real provinces • then, for incorrect guesses… def province. Challenge( prov ): prov['incorrect']=0 while 0 in prov. values(): guess = input("Guess: ") if guess not in prov: print('Try again. . . ’) prov['incorrect'] += 1 elif prov[guess] == 0: print('Yes!’) prov[guess] += 1 else: print('Already guessed. . . ‘) prov[guess] += 1
Based on fav. Child, write fav. GChild to return the first grandchild alphabetically - or return 'no one' if there are none. def fav. Child( person, Tree ): if person in Tree: Kids = Tree[person] Kids. sort() return Kids[0] else: return 'no children'
Based on fav. Child, write fav. GChild to return the first grandchild alphabetically - or return 'no one' if there are none. def fav. Child( person, Tree ): if person in Tree: Kids = Tree[person] Kids. sort() return Kids[0] else: return 'no children' def fav. GChild( person, Tree ): g. Children = [] if person in Tree : for child in Tree[person]: if child in Tree: g. Children += Tree[child] if g. Children == []: return 'no one' else: g. Children. sort() return g. Children[0]
EECS 110 today A whole new class of programming The Date class HW 6 Details Pr 1 (the Date class) Pr 2 (the Connect 4 Board) Due Sunday Pr 3 (the Connect 4 Player (e. c. )) Projects Fri. , 5/25: online Wed. , 5/30: class Projects Tue. , 5/29: recitation, W. lab Fri. , 6/1: recitation Lab and HW #6 Final! Mon. , 6/4: rev. for final Wed. , 6/6: final
Lists, Tuples, Dictionaries, … + lots of computer work for the programmer's work! e. g. , the Simpson's dictionary… T = {'abe' : ['homer', 'herb'], 'jackie': ['marge', 'patty', 'selma'], 'homer' : ['hugo', 'bart', 'lisa', 'maggie'], 'marge' : ['hugo', 'bart', 'lisa', 'maggie']}
Lists, Tuples, Dictionaries, … + - lots of computer work for the programmer's work! fairly generic capabilities, e. g. , len, print limited to square-bracket naming, e. g. , no options as to data organization… list A T = {'abe' 42 int A[0] 3. 1 float A[1] A[i] A = [ 42, 3. 1, '!'] '!' str A[2] : ['homer', 'herb'], …} T. get. Children('abe') NOT POSSIBLE! have to use T['abe']
Lists, Tuples, Dictionaries, … + - lots of computer work for little programmer work! fairly generic capabilities, e. g. , len, print limited to square-bracket naming, e. g. , no options as to data organization… list A 42 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. There will typically be MANY objects of a single class.
Examples… Python's class libraries… http: //docs. python. org/lib/ Graphics libraries
Using objects and classes: A particularly complex example… >>> z = 3 + 4 j >>> 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 -4 j 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.
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
Date This is a class. It is a user-defined datatype (that you'll build in Lab this week!) >>> d = Date(1, 1, 2016) this is a CONSTRUCTOR … >>> d 1/1/2016 this is an object of type Date the representation of a particular object of type Date >>> d. is. Leap. Year() True the is. Leap. Year method returns True or False. How does it know what year to check? >>> d 2 = Date(12, 31, 2017) >>> d 2 Another object of type Date again, via the constructor. 12/31/2017 >>> d 2. is. Leap. Year() 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 The Date class def __repr__( self ): """ used for printing Dates """ s = "%02 d/%04 d" % (self. month, self. day, self. year) return s def is. Leap. Year( self ): """ anyone know the rule? """
self is the specific OBJECT THAT CALLS A METHOD >>> d = Date(1, 1, 2016) >>> d 1/1/2016 These methods need access to the object that calls them >>> d. is. Leap. Year() True >>> d 2 = Date(12, 31, 2017) >>> d 2 12/31/2017 >>> d 2. is. Leap. Year() False 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) def is. Leap. Year( self ): """ here it is """ if self. year%400 == 0: return True if self. year%100 == 0: return False if self. year%4 == 0: return True return False
Date >>> d = Date(1, 1, 2017) always created with the CONSTRUCTOR … >>> d 1/1/2017 >>> d. yesterday() >>> d the yesterday method returns nothing at all. Is it doing anything? d has changed! 12/31/2016 >>> d. sub. NDays(35) Why is this important? lots of printing… >>> d Some methods return a value; others change the object that call it!
Date ids >>> d = Date(11, 10, 2017) >>> d 11/10/2017 >>> d 2 = Date(11, 2017) >>> d 2 11/11/2017 >>> d == d 2 ? >>> d 2. yesterday() >>> d == d 2 ? this initializes a different Date!
Date ids >>> d = Date(11, 10, 2017) >>> d 11/10/2017 >>> d 2 = Date(11, 2017) >>> d 2 11/11/2017 >>> d == d 2 False >>> d 2. yesterday() >>> d == d 2 ? this initializes a different Date!
Date ids >>> d = Date(11, 10, 2017) >>> d 11/10/2017 >>> d 2 = Date(11, 2017) >>> d 2 11/11/2017 >>> d == d 2 False >>> d 2. yesterday() >>> d == d 2 False this initializes a different Date!
Double Date >>> d = Date(11, 10, 2017) >>> d 11/10/2017 >>> d. add. NDays(36) >>> d 2 ? >>> d 2 = d. copy() >>> d 2 == d ? >>> d. equals(d 2) ?
Double Date >>> d = Date(11, 10, 2017) >>> d 11/10/2017 >>> d. add. NDays(36) >>> d 2 12/16/2017 >>> d 2 = d. copy() >>> d 2 == d ? >>> d. equals(d 2) ?
Double Date >>> d = Date(11, 10, 2017) >>> d 11/10/2017 >>> d. add. NDays(36) >>> d 2 12/16/2017 >>> d 2 = d. copy() >>> d 2 == d False >>> d. equals(d 2) ?
Double Date >>> d = Date(11, 10, 2017) >>> d 11/10/2017 >>> d. add. NDays(36) >>> d 2 12/16/2017 >>> d 2 = d. copy() >>> d 2 == d False >>> d. equals(d 2) True
class Date: More Date def __init__( self, mo, dy, yr ): def __repr__(self): def is. Leap. Year(self): def copy(self): """ returns a DIFFERENT object w/SAME date! """ def equals(self, d 2): """ returns True if they represent the same date; False otherwise """
class Date: More Date def __init__( self, mo, dy, yr ): def __repr__(self): def is. Leap. Year(self): def copy(self): """ returns a DIFFERENT object w/SAME date! ""“ return Date(self. month, self. day, self. year) def equals(self, d 2): """ returns True if they represent the same date; False otherwise """
class Date: More Date def __init__( self, mo, dy, yr ): def __repr__(self): def is. Leap. Year(self): def copy(self): """ returns a DIFFERENT object w/SAME date! ""“ return Date(self. month, self. day, self. year) def equals(self, d 2): """ returns True if they represent the same date; False otherwise ""“ return self. month == d 2. month and self. day == d 2. day and self. year == d 2. year
class Date: This method is WRONG! Find why … and suggest how you could fix it! def is. Before(self, d 2): """ if self is before d 2, this should return True; else False """ if self. year < d 2. year: return True if self. month < d 2. month: return True if self. day < d 2. day: return True return False def tomorrow(self): """ moves the date that calls it ahead 1 day """ DIM = [0, 31, 28, 31, 30, 31] "Quiz" Write this tomorrow method. It does not return anything. It just CHANGES the date object that calls it.
class Date: What's wrong? def is. Before(self, d 2): """ if self is before d 2, this should return True; else False """ if self. year < d 2. year: return True if self. month < d 2. month: return True if self. day < d 2. day: return True return False
def is. Before(self, d 2): """ Returns true if self is before d 2 """ if self. year < d 2. year: return True if self. month < d 2. month and self. year == d 2. year: return True if self. day < d 2. day and d 2. month == self. month and self. year == d 2. year: return True return False
class Date: def tomorrow(self): """ moves the date that calls it ahead 1 day """ DIM = [0, 31, 28, 31, 30, 31] # Leap years not accounted for self. day +=1 if self. day > DIM[self. month]: self. day = 1 self. month += 1 if self. month > 12: self. month = 1 self. year += 1
Lab tomorrow Add to Date these methods yesterday(self) tomorrow(self) add. NDays(self, N) sub. NDays(self, N) is. Before(self, d 2) is. After(self, d 2) diff. Debug(self, d 2) dow(self) and use your Date class to analyze our calendar a bit…
See you in Lab !
- Slides: 36