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.

Slides:



Advertisements
Similar presentations
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Advertisements

EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University
"Intelligent" CS 5 An object is structured data that is alive, responsible, and intelligent. Sound too friendly? This week’s objects and classes will be.
HW 6: Problems 2&3 Simulating Connect 4.
Modules and Objects Introduction to Computing Science and Programming I.
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Snick  snack CPSC 121: Models of Computation 2010 Winter Term 2 DFAs in Depth Benjamin Israel Notes heavily borrowed from Steve Wolfman’s,
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
CS 106 Introduction to Computer Science I 03 / 19 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
CS 5 Today: two I's AIUI hw11pr2.py an arbitrarily-good Connect 4 player! Player class Extra: scoreBoard4Tourney an intuitive Connect 4 player: hw11pr1.html.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
ICAPRG301A Week 4Buggy Programming ICAPRG301A Apply introductory programming techniques Program Bugs US Navy Admiral Grace Hopper is often credited with.
Nelson Series Talk Wed, 11/10 7:00 pm Security, Liberties and Trade-offs in the War on Terrorism Since 9/11, we have enacted the Patriot Act, tighter screening.
CSC 212 Object-Oriented Programming and Java Part 1.
IS 313 Today Schedule Week 0: Classes Objects You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where.
Def tomorrow(self): """Changes the calling object so that it represents one calendar day after the date it originally represented. """ if self.month in.
Data Collections: Dictionaries CSC 161: The Art of Programming Prof. Henry Kautz 11/4/2009.
Now String theory To Do: Lists This stuff hurts my brane. when you learn string theory from google images… Goal: Thinking like a machine You should now.
60 Questions (review for final exam) CSC 161: The Art of Programming Prof. Henry Kautz 12/7/
IS313 Today: two I's AIUI hw9pr1.py an arbitrarily-good Connect 4 player! Player class Hw 10 (project) I wish there were three i's! Hw 9 is due Wed., 12/23.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Looping and Counting Lecture 3 Hartmut Kaiser
HW 6: Problems 2 & 3 Simulating Connect 4. HW 6: Overview Connect 4: Variation of Tic-Tac-Toe – Board: Vertical 7x6 – Two players take alternating move.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
Lists, Tuples, Dictionaries, … + lots of computer work for the programmer's work! T = {'abe' :['homer','herb'], 'jackie':['marge','patty','selma'], 'homer'
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
CS 106 Introduction to Computer Science I 10 / 29 / 2007 Instructor: Michael Eckmann.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
OOP with Objective-C Categories, Protocols and Declared Properties.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
Program Organization Sequential Execution: One line done after the other Conditional Execution: If a test is true, one section is done, otherwise another.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Written by: Dr. JJ Shepherd
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
IS 313 Today Schedule Week 0: files dictionaries You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where we've been… Where.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #003 (February 14, 2015)
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Homework 10 Due ( MT sections ) ( WTh sections ) at midnight Sun., 11/10 Mon., 11/11 Problems
IS313 Tomorrow… Wednesday, Nov Classes + Objects, part 2 Wednesday, Nov Classes + Objects, part 3 Thursday, Nov Date class due Thursday,
EECS 110: Lec 14: Classes and Objects
CMSC201 Computer Science I for Majors Lecture 25 – Classes
EECS 110: Lec 15: Classes and Objects (2)
EECS 110: Lec 17: Review for the Final Exam
Hello World! CSE442.
Introduction to Object-Oriented Programming (OOP)
Intelligent CS 5 ? This week's objects will be more adversarial…
This week's classes Connect 4 aiMove
This week's classes Connect 4 Player
Introduction to Computer Programming
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Introduction to Object-Oriented Programming (OOP)

EECS 110: Lec 14: Classes and Objects
EECS 110: Lec 15: Classes and Objects (2)
Introduction to Object-Oriented Programming (OOP)
Introduction to Object-Oriented Programming (OOP) II
Presentation transcript:

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!) 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 str A A[0]A[1] A[2] A = [ 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 str A A[0]A[1] A[2] A = [ 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

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

object ive Advantages: abs(z) == z.__abs__() real = 3.0 imag = def __abs__(): return sqrt(self.real**2 + self.imag**2)... r = 5.0 theta = 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 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.

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

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?

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?

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

Connect Four | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O| 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

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)

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

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

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

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?

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

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