Intro to objects - Northwestern University

Document Sample
Intro to objects - Northwestern University Powered By Docstoc
					                     EECS 110: Lec 14:
                   Classes and Objects



                       Aleksandar Kuzmanovic
                       Northwestern University

http://cs.northwestern.edu/~akuzma/classes/EECS110-s09/
              EECS 110 today FIXME
           A whole new class of programming

       HW6 Details                                    The Date class
  Pr1 (the Date class)                                Lab and HW #6
  Pr2 (the Connect4Board)         Due Sunday 5/24
  Pr3 (the Connect4Player (e.c.))            EECS    110 Hall of Fame




   Projects                  Projects                      Final week!
Fri., 5/22: online   Fri., 5/29: recitation (G15)    Mon., 6/1: rev. for final
Wed., 5/27: class    Tue., 6/2: recitation, W. lab       Wed., 6/3, Final
       EECS110 Hall of Fame
                 Richard Pang




                                Leo Zhu




Michael Seeley
        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.,           A[i]

         no options as to data organization…
                                                     A = [ 42, 3.1, '!']

                               42      3.1     '!'
                  list       int     float    str
                   A         A[0]     A[1]    A[2]

T = {'abe'   :['homer','herb'],
     …}
T.getChildren('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.,         A[i]
    no options as to data organization…
                                              A = [ 42, 3.1, '!']
                          42     3.1    '!'
             list       int    float   str
              A         A[0]    A[1]   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…                          Graphics libraries


       Python's class libraries…




 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                                   a data member of all objects
                                                of class complex
                    its value for
   4.0              this object, z



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

>>> d
                     this is an object of type Date
1/1/2008
               the representation of a particular object of type Date


>>> d.isLeapYear()               the isLeapYear method returns
                                 True or False. How does it know
True                             what year to check?


>>> d2 = Date(12,31,2007)
                                              Another object of type Date -
>>> d2                                        again, via the constructor.


12/31/2007
>>> d2.isLeapYear()                How does it know to return False,
                                   instead of True in this case ??
False
class Date:
    """ a blueprint (class) for objects
        that represent calendar days
                                             The Date
    """                                        class
    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? """
        self          is the specific OBJECT THAT
                           CALLS A METHOD


>>> d = Date(1,1,2008)
>>> d                        These methods need
                             access to the object
1/1/2008                       that calls them



>>> d.isLeapYear()
True

>>> d2 = Date(12,31,2007)
>>> d2                            These methods need
                                  access to the object
12/31/2007                          that calls them

>>> d2.isLeapYear()
False
              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.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,2008)                always created with the
                                      CONSTRUCTOR …
>>> d
1/1/2008

>>> d.yesterday()       the yesterday method returns
                        nothing at all. Is it doing anything?
>>> d                d has changed!
12/31/2007
>>> d.subNDays(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,2008)    this initializes a different Date!

>>> d
11/10/2008
>>> d2 = Date(11,11,2008)
>>> d2
11/11/2008

>>> d == d2
?
>>> d2.yesterday()
>>> d == d2
?
         Date ids
>>> d = Date(11,10,2008)    this initializes a different Date!

>>> d
11/10/2008
>>> d2 = Date(11,11,2008)
>>> d2
11/11/2008

>>> d == d2
False
>>> d2.yesterday()
>>> d == d2
?
         Date ids
>>> d = Date(11,10,2008)    this initializes a different Date!

>>> d
11/10/2008
>>> d2 = Date(11,11,2008)
>>> d2
11/11/2008

>>> d == d2
False
>>> d2.yesterday()
>>> d == d2
False
                     Double Date

>>> d = Date(11,10,2008)
>>> d
11/10/2008
>>> d.addNDays(36)
>>> d2
?
>>> d2 = d.copy()
>>> d2 == d
?
>>> d.equals(d2)
?
                     Double Date

>>> d2 = d
>>> d
11/10/2008
>>> d.addNDays(36)
>>> d2
12/16/2008
>>> d2 = d.copy()
>>> d2 == d
?
>>> d.equals(d2)
?
                     Double Date

>>> d2 = d
>>> d
11/10/2008
>>> d.addNDays(36)
>>> d2
12/16/2008
>>> d2 = d.copy()
>>> d2 == d
False
>>> d.equals(d2)
?
                     Double Date

>>> d2 = d
>>> d
11/10/2008
>>> d.addNDays(36)
>>> d2
12/16/2008
>>> d2 = d.copy()
>>> d2 == d
False
>>> d.equals(d2)
True
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
        """
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! ""“
         return Date(self.month, self.day, self.year)



    def equals(self, d2):
        """ returns True if they represent
            the same date; False otherwise
        """
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! ""“
         return Date(self.month, self.day, self.year)



    def equals(self, d2):
        """ returns True if they represent
            the same date; False otherwise
        ""“
         return self.month == d2.month and
                self.day == d2.day and
                self.year == d2.year
class Date:

  def isBefore(self, d2):
                             This method is WRONG! Find why …
                               and suggest how you could fix it!        "Quiz"
     """ 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 """                     Write this
     DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31]                    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
def isBefore(self, d2):
   """ Returns true if self is before d2 """
   if self.year < d2.year:
       return True
   if self.month < d2.month and self.year == d2.year:
       return True
   if self.day < d2.day and d2.month == self.month and \
           self.year == d2.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,30,31,31,30,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)
   addNDays(self, N)
   subNDays(self, N)
   isBefore(self, d2)
   isAfter(self, d2)
   diff(self, d2)
   diffDebug(self, d2)
   dow(self)


                                    and use your Date class to
                                   analyze our calendar a bit…
See you in Lab !

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:0
posted:4/7/2013
language:Unknown
pages:32