Http://xkcd.com/.

Slides:



Advertisements
Similar presentations
EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University
Advertisements

"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.
9-May-15 Notes on Style Testing the TicTacToe game.
HW 6: Problems 2&3 Simulating Connect 4.
Lists Introduction to Computing Science and Programming I.
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.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
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.
Invitation to Computer Science, Java Version, Second Edition.
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.
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.
Exceptions Handling Exceptionally Sticky Problems.
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
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.
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.
Ionut Trestian Northwestern University
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
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.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
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,
CSC 108H: Introduction to Computer Programming Summer 2012 Marek Janicki.
Reading Files >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() In Python reading files is no.
CSC 108H: Introduction to Computer Programming
EECS 110: Lec 14: Classes and Objects
EECS 110: Lec 15: Classes and Objects (2)
Software Development.
CS this week 4 Building classes vs. using the library hw10pr2
EECS 110: Lec 13: Dictionaries
EECS 110: Lec 12: Mutable Data
EECS 110: Lec 17: Review for the Final Exam
COMPSCI 107 Computer Science Fundamentals
Introduction to Python
Handling Exceptionally Sticky Problems
Introduction to Object-Oriented Programming (OOP)
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Intelligent CS 5 ? This week's objects will be more adversarial…
This week's classes Connect 4 aiMove
Testing UW CSE 160 Spring 2018.
CSE 341: Programming Languages Section 1
CS 106A, Lecture 19 ArrayLists
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Testing UW CSE 160 Winter 2016.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Ionut Trestian Northwestern University
Introduction to Object-Oriented Programming (OOP)
Topic 1: Problem Solving
Topic 1: Problem Solving
Coding Concepts (Basics)
EECS 110: Lec 14: Classes and Objects
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
HW 6: Problems 2 & 3 Simulating Connect 4.
CS this week 4 Building classes vs. using the library hw10pr2
Northwestern University
HW 6: Problems 2 & 3 Simulating Connect 4.
Handling Exceptionally Sticky Problems
EECS 110: Lec 15: Classes and Objects (2)
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
EECS 110: Lec 12: Mutable Data
Introduction to Object-Oriented Programming (OOP)
Introduction to Object-Oriented Programming (OOP) II
Lecture 6 - Recursion.
Presentation transcript:

http://xkcd.com/

IS 313 Today Schedule Week 0: Week 4: Week 1: Week 5: Week 2: Week 6: Where we've been… Week 0: Week 4: Functions and Data Loops and language Week 1: Week 5: Week 2: Week 6: Classes Where we're going… Week 8: Week 12: 42 'a' Projects and Networks Dictionaries and Classes key value Week 9: Week 13: Week 10: Week 14: a Dictionary object… You're saying that Python's got class? Objects

Watch out! http://www.youtube.com/watch?v=nBeUGqeYsQg

Python ~ an object-oriented programming language Objects "Oh yeah!" 42 'a' key value Data reigns a Dictionary object… a String object… Python ~ an object-oriented programming language Classes input Methods Functions output Types

Some languages are ALL OBJECTS! Almost all data in Java are OBJECTS The CLASS of an objects is its type. METHODS are f'ns ~ "part of the data"! Now it's data that's royalty!

Lists vs. Dictionaries Lists are not perfect… If I had a dictionary, I guess I could look up what it was! Lists vs. Dictionaries Lists are not perfect… reference 5 42 You can't choose what to name data. L L[0] L[1] L[0], L[1], … You have to start at 0. L[1985] = 'ox' L[1986] = 'tiger' Some operations can be slow for big lists … if 'tiger' in L:

pop deletes a key and returns its value More on dictionaries They don't seem moronic to me! Dictionaries have lots of built-in methods, or functions: >>> d = {1990: 'horse', 1991: ram'} >>> d.keys() [ 1990, 1991 ] >>> d.has_key( 1991 ) True >>> d.has_key( 1969 ) False >>> d.pop( 1988 ) 'dragon' keys returns a list of all keys has_key checks if a key is present pop deletes a key and returns its value

Methods Functions d.has_key( 1991 ) has_key( 1991, d ) There's madness in this method! d.has_key( 1991 ) are functions that are called by the data itself! Functions has_key( 1991, d ) all data must be passed in as function inputs… are called on their own… Warning: this has_key function is for example purposes only. It does not exist!

Design-it-yourself data. Classes and Objects Design-it-yourself data.

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.

(1) A class is a type of 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.

(1) A class is a type of 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.

A particularly appropriate reference … Using objects and classes: A particularly appropriate reference … >>> d = dict() an example of the dictionary constructor >>> d['answer'] = 42 >>> dir(d) all of the data members and methods of the dictionary class (and thus the object d !) >>> d.keys() [ 'answer' ] >>> d.values() [ 42 ] two methods (functions) within all objects of class dictionary

The CONSTRUCTOR … Code class dict: """ a dictionary class """ def __init__( self ): """ the CONSTRUCTOR """ # sets all of the data needed # there's no data here! Comments the constructor is named __init__ but is used via the class name defines a new datatype called dict It sets all the DATA MEMBERS of a new object the object is called self

The REPR … Code Comments class dict: """ a dictionary class """ def __repr__( self ): """ a grim method """ s = '{' for key in self.keys(): s += str(key) + ':' s += str( self[key] ) + ', ' s += '}' return s Comments this method is named __repr__ and it provides a string that will be used when printing the object being printed is called self the string to print gets returned

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 variables of that type data members: data an object contains methods: functions an object contains benefits: encapsulation & abstraction An object is alive, responsible, and intelligent. - C++ FAQs

Examples… Python's class libraries… Graphics libraries Do reference libraries have library references? http://docs.python.org/lib/ >>> f = urllib.urlopen( 'http://www.cs.hmc.edu/~dodds/IS313/HW/index.html' ) >>> text = f.read() >>> text[:50]

usually called "methods" instead of functions 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 User-defined structures that become part of the language (at least locally…)

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

Date We want (or need) to represent lots of interacting calendar days This is a class. It is a user-defined datatype (that you'll build in Lab this week!) We want (or need) to represent lots of interacting calendar days The Problem The Design What data should be set in the constructor? Are you asking what Date-a a Date needs? What functionality will we need to support? d.dow() usually some, but not all, is known beforehand

Using Dates >>> d = Date(1,1,2012) >>> d 1/1/2012 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(11,4,2009) >>> d2 11/4/2009 >>> 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 ??

The Date class class Date: def __init__( self, m, d, y ): """ the Date constructor """ self.month = m self.day = d self.year = y def __repr__( self ): """ used for printing Dates """ s = "%02d/%02d/%04d" % (self.month, self.day, self.year) return s def isLeapYear( self ): The Date class Why is everyone so far away?!

self is the specific OBJECT THAT CALLED THE METHOD ! >>> d = Date(1,1,2012) >>> d 1/1/2012 These methods need access to the object that calls them >>> d.isLeapYear() True >>> d2 = Date(12,31,2011) >>> d2 12/31/2011 >>> d2.isLeapYear() False These methods need access to the object that calls them Why not use d?

Which leap is correct? def isLeapYear( self ): """ left-side leap """ if self.yr%400 == 0: return True elif self.yr%100 == 0: return False elif self.yr%4 == 0: else: def isLeapYear( self ): """ right-side leap """ if self.yr%4 == 0: return True elif self.yr%100 == 0: return False elif self.yr%400 == 0: else:

a Leap of faith…. class Date: def isLeapYear( self ): How about a 4000-year rule? 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

Date objects are mutable but only if we want them to be! >>> d = Date(1,1,2008) >>> d 01/01/2008 always created with the CONSTRUCTOR … >>> d.yesterday() >>> d 12/31/2007 >>> d.tomorrow() 01/01/2008 the yesterday method returns nothing at all. Is it doing anything? d has changed! Some methods return a value; others (like this one) change the object that call it!

Date ids >>> d = Date(11,4,2009) >>> d 11/4/2009 What date is on your id? What id is on your Date? >>> d = Date(11,4,2009) >>> d 11/4/2009 >>> d2 = Date(11,5,2009) >>> d2 11/5/2009 >>> d == d2 Will these be true or false? >>> d2.yesterday() >>> d == d2 >>> d.equals( d2 )

Double Date >>> d2 = d >>> d 11/4/2009 Excuse me -- ids please! >>> d2 = d >>> d 11/4/2009 >>> d.yesterday() >>> >>> d2 >>> d2 == d >>> d2.equals(d) What happens here?

Using copy >>> d2 = d.copy() >>> d 11/3/2009 But where does copy come from? >>> d2 = d.copy() >>> d 11/3/2009 >>> d2 >>> d.yesterday() >>> d2 == d What happens here?

Where are these TWO inputs coming from? 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 """ Where are these TWO inputs coming from?

Try it… 1/1/2010 11/4/2009 class Date: def isBefore(self, d2): """ True if self is before d2 """ if self.yr < d2.yr: return True if self.mo < d2.mo: return True if self.dy < d2.dy: return True return False 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] Try it… Why is this method WRONG for the dates 1/1/2010 11/4/2009 how might you fix this problem? This tomorrow method should not return anything. It just CHANGES the date object that calls it. DIM might be helpful…

Why is this method WRONG for the dates class Date: def isBefore(self, d2): """ True if self is before d2 """ if self.yr < d2.yr: return True if self.mo < d2.mo: return True if self.dy < d2.dy: return True return False What's wrong? Why is this method WRONG for the dates 1/1/2010 11/4/2009

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]

HW today / tomorrow Add these methods to Date copy(self) equals(self, d2) 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… Prof. Art Benjamin no computer required…

Unusual calendar years…

Application #2… Aargh! Python has no Connect-four datatype… | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O| --------------- 0 1 2 3 4 5 6 Aargh! … but we can correct that! Can I see a demo?

Designing classes 1) What data? (Data Members) Not limited to 7x6! 2) What are objects' crucial capabilities? (Methods)

Connect Four: the object b int str str str str list width Board b data int str str str str height str str str str data What is the name of the method that will construct this data?

Connect Four: constructor class Board: """ a datatype representing a C4 board with an arbitrary number of rows and cols """ def __init__( self, width, height ): """ the constructor for objects of type Board """ self.width = width self.height = height self.data = [] # this will be the board for row in range( 6 ): boardRow = [] for col in range( 7 ): boardRow += [' '] # add a space to this row self.data += [boardRow] Bad magic?

Connect Four: the object b int str str str str list width Board b data int str str str str height str str str str | | | | | | | | | | | |X| | | | | |X| |X|O| | | |X|O|O|O|X| |O| --------------- 0 1 2 3 4 5 6 What is the name of the method that will print this data?

Connect Four: __repr__ def __repr__(self): """ this method returns a string representation for an object of type Board """ s = '' for row in range( 6 ): s += '|' for col in range( 7 ): s += self.data[row][col] + '|' s += '\n' return s which row is row 0, row 1, and so on? To remove? To add?

Examples def addMove(self, col, ox): row = self.height-1 while True: if self.data[row][col] == ' ': self.data[row][col] = ox row -= 1 def allowsMove(self, col): a C4 board col # 'X' or 'O' Step through this addMove method. How does it work? What's wrong? allowsMove should return True if col is a valid move; False otherwise.

C4 Board class: methods Which is trickiest… ? the “constructor” __init__( self, width, height ) checks if allowed allowsMove( self, col ) places a checker addMove( self, col, ox ) removes a checker delMove( self, col ) __repr__( self ) outputs a string isFull( self ) checks if any space is left winsFor( self, ox ) checks if a player has won hostGame( self ) play! Which is trickiest… ?

Checking wins… ? b X O Thoughts? corner cases?

Thinking about final projects… Lab … and hw questions

There are several well-made, concise tutorials… want to brush up on anything?

Two good references for looking up syntax… wikipedia, for sure http://www.cis.upenn.edu/~matuszek/General/JavaSyntax/ for checking out just one thing!

"thinking like a computer" or, at least, like Java. Aha! But what is this I see? data Constructors are giving me a HEAP of trouble! constructor(s) Data members Constructor – creates data objects on the heap 48