EECS 110: Lec 14: Classes and Objects

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.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Introduction to Python
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Methods in Computational Linguistics II Queens College Lecture 7: Structuring Things.
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.
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.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 5: List Comprehensions Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
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.
Object Oriented Programing (OOP)
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
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.
EECS 110: Lec 13: Dictionaries Aleksandar Kuzmanovic Northwestern University
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
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.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Introduction to Computing Science and Programming I
EECS 110: Lec 10: Definite Loops and User Input
EECS 110: Lec 15: Classes and Objects (2)
CS this week 4 Building classes vs. using the library hw10pr2
EECS 110: Lec 13: Dictionaries
EECS 110: Lec 12: Mutable Data
Types CSCE 314 Spring 2016.
CS1022 Computer Programming & Principles
EECS 110: Lec 17: Review for the Final Exam
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Introduction to Python
EECS 110: Lec 5: List Comprehensions
EECS 110: Lec 5: List Comprehensions
Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning
CS-104 Final Exam Review Victor Norman.
Today’s Objectives Review the important points of classes
CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions Dan Grossman Winter 2013.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Introduction to Object-Oriented Programming (OOP)
Introduction to Computer Programming
Introduction to Object-Oriented Programming (OOP) II
Random Numbers In today’s lesson we will look at:
CS190/295 Programming in Python for Life Sciences: Lecture 6
CMSC201 Computer Science I for Majors Lecture 12 – Tuples
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Introduction to Object-Oriented Programming (OOP)

CSE 341 PL Section 2 Justin Harjanto.
EECS 110: Lec 14: Classes and Objects
CS this week 4 Building classes vs. using the library hw10pr2
COMPUTER 2430 Object Oriented Programming and Data Structures I
Python Review
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
Functions, Procedures, and Abstraction
Presentation transcript:

EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University http://networks.cs.northwestern.edu/EECS110-s17/

“Quiz” def favChild( person, Tree ): if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' 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… Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none. def provinceChallenge( 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 favGChild( person, Tree ):

def provinceChallenge( prov ): while 0 in prov.values(): 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 provinceChallenge( 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 provinceChallenge( prov ): prov['incorrect']=0 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 provinceChallenge( 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...‘)

def favChild( person, Tree ): if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none.

def favGChild( person, Tree ): gChildren = [] if person in Tree : def favChild( person, Tree ): if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none. def favGChild( person, Tree ): gChildren = [] if person in Tree : for child in Tree[person]: if child in Tree: gChildren += Tree[child] if gChildren == []: return 'no one' else: gChildren.sort() return gChildren[0]

A whole new class of programming EECS 110 today A whole new class of programming The Date class HW6 Details Pr1 (the Date class) Lab and HW #6 Pr2 (the Connect4Board) Pr3 (the Connect4Player (e.c.)) Due Sunday Projects Projects Final! Fri., 5/19: online Fri., 5/26: recitation Tue., 5/30: recitation, W. lab Wed., 5/24: rev. for final Wed., 5/31, final Mon., 5/22: class

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']} We can use built-in functions, etc.

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

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

Python's class libraries… Examples… Graphics libraries Python's class libraries… http://docs.python.org/lib/

A particularly complex example… 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 4.0 >>> z.conjugate() 3-4j a data member of all objects of class complex its value for this object, z a method (function) within all objects of class complex 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.

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

Date >>> d = Date(1,1,2016) >>> d 1/1/2016 This is a class. It is a user-defined datatype (that you'll build in Lab this week!) >>> d = Date(1,1,2016) >>> d 1/1/2016 this is a CONSTRUCTOR … 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(12,31,2017) >>> d2 12/31/2017 >>> 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: """ 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

is the specific OBJECT THAT CALLS A METHOD 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.isLeapYear() True >>> d2 = Date(12,31,2017) >>> d2 12/31/2017 >>> d2.isLeapYear() False These methods need access to the object that calls them

a Leap of faith…. class Date: def isLeapYear( self ): 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,2017) >>> d 1/1/2017 always created with the CONSTRUCTOR … >>> d.yesterday() >>> d 12/31/2016 >>> d.subNDays(35) lots of printing… the yesterday method returns nothing at all. Is it doing anything? d has changed! Why is this important? Some methods return a value; others change the object that call it!

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

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

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

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

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

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

Double Date >>> d = Date(11,10,2017) >>> d 11/10/2017 >>> d.addNDays(36) >>> d2 12/16/2017 >>> d2 = d.copy() >>> d2 == d False >>> d.equals(d2) True

More Date class Date: def copy(self): 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 class Date: def copy(self): 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 """

More Date class Date: def copy(self): 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

"Quiz" 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 """ DIM = [0,31,28,31,30,31,30,31,31,30,31,30,31] "Quiz" 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.

""" if self is before d2, this should return True; else False """ 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? 5/1/2017 vs 8/1/2010 won’t work correctly.

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: if self.day < d2.day and d2.month == self.month and \ self.year == d2.year: 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 !