A whole new class of programming

Preview:

DESCRIPTION

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). - PowerPoint PPT Presentation

Citation preview

A whole new class of programming

CS 5 today

HW10: Due Sun, Nov 15

Pr0: Ariane 5 Reading

Pr1/Lab: the Date classPr2 Connect4BoardPr3 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

Software Engineering

creating and composing functions

Building atop the work of others…

Insight into details, e.g., data storage and retrieval.

Invention, not reinvention.

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.

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

Lists, Tuples, Dictionaries, …

+ lots of functionality with very little programmer work

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 strA A[0] A[1] A[2]

A = [ 42, 3.1, '!']

42 3.1 '!'

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 strA A[0] A[1] A[2]

A = [ 42, 3.1, '!']

42 3.1 '!'

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…

Do reference libraries have

library references?

Python's class libraries…

Graphics libraries

http://docs.python.org/lib/

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

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:

abs(z) == z.__abs__()

real = 3.0imag = 4.0...def __abs__(): return sqrt(self.real**2 + self.imag**2)...

r = 5.0theta = 0.927...def __abs__(): return r

...

my complex numbera Python complex number

z??

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 representation 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.

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

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

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?

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!

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!

What date is on your id?

What id is on your Date?

>>> d == d2?

>>> d2.yesterday()

>>> d == d2

?

Double Date

>>> d2 = d

>>> d

11/26/2007

>>> d.addNDays(36)

>>> d2

?

>>> d2 = d.copy()

>>> d2 == d

?

>>> d.equals(d2)

?

Excuse me -- ids please!

How many Dates are here?

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

selfish?

"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.

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?

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]

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…

Unusual calendar years…

But Why ?

• Flexibility

• Reusability

• Abstraction

ordinary data structures

create-your-own

write once, take anywhere

worry once, use anywhere

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

| | | | | | | || | | | | | | || | | | | | | || | | |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... !

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

Coursec

def addStudent(self, student)

String

list

float

name

CL

hours

String 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)

Coursec

def addStudent(self, student)

String

list

float

name

CL

hours

String 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

Connect Four: the object b

This is true for sufficiently broad definitions of “the creators of Python’s library” ...

Boardb

def addMove(self, col, player)

intNROWS

intNCOLS

def allowsMove(self, col)

char char char

char char char

char char char

datalist char

char

char

def winsFor(self, player)

data members

methods

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.

Connect Four: the object b

This is true for sufficiently broad definitions of “the creators of Python’s library” ...

Boardb

def addMove(self, col, player)

intNROWS

intNCOLS

def allowsMove(self, col)

char char char

char char char

char char char

datalist char

char

char

def winsFor(self, player)

data members

methods

What is player ?

Connect Four: the object b

This is true for sufficiently broad definitions of “the creators of Python’s library” ...

Boardb

def addMove(self, col, player)

intNROWS

intNCOLS

def allowsMove(self, col)

char char char

char char char

char char char

datalist char

char

char

def winsFor(self, player)

data members

methods

Which methods will alter b? Which leave it alone?

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?

Connect Four: Boardclass 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 !

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?

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?

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!

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