CSC148: Week 1

Similar documents
CSC148: Week 2

CSC148 Summer 2018: Assignment 1

CSC148: Week 4

Question 1. CSC 148H1 Term test #1 Solutions February [8 marks]

CSC148 Recipe for Designing Classes

Lecture 17: Classes (Chapter 15)

CIS192: Python Programming

Credit: The lecture slides are created based on previous lecture slides by Dan Zingaro.

Lecture 17: Classes (Chapter 15)


Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

61A Lecture 3. Friday, September 5

MITOCW watch?v=flgjisf3l78

Lecture 3. Functions & Modules

CSC148H Week 1 >> COURSE INFORMATION, RECAP, OOP. Sadia Rain Sharmin Week of May 7, 2018

Instructor: Craig Duckett. Lecture 04: Thursday, April 5, Relationships

CS 241 Data Organization using C

CSC148 Intro. to Computer Science

PREPARING FOR THE FINAL EXAM

Lecture 18. Methods and Operations

CS 241 Data Organization. August 21, 2018

Lecture 2: Variables & Assignments

CS Homework 4 Employee Ranker. Due: Wednesday, February 8th, before 11:55 PM Out of 100 points. Files to submit: 1. HW4.py.

PREPARING FOR PRELIM 1

The following content is provided under a Creative Commons license. Your support

def function1(l: 'list of numbers') -> None: ''' Print, one per line, double the value of each item in the parameter '''

CSE : Python Programming

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

CSC148 Intro. to Computer Science

WELCOME TO CS 16! Enrollment status: 117/ Problem Solving with Computers-I

Class extension and. Exception handling. Genome 559

Advanced topics, part 2

Welcome to CSC148! Introduction to Computer Science

Lecture 19. Operators and Abstraction

Exception Handling. Genome 559

MITOCW watch?v=9h6muyzjms0

Advanced Programming Concepts. CIS 15 : Spring 2007

Lecture 1. Course Overview, Python Basics

Review 2. Classes and Subclasses

CS1 Lecture 13 Feb. 13, 2019

Class extension and. Exception handling. Genome 559

PREPARING FOR PRELIM 2

Object-Oriented Python

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

UNIVERSITY OF TORONTO Faculty of Arts and Science. Midterm 1 CSC148H1F L0201 (Liu)

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

CS/ENGRD 2110 FALL 2018

Quiz 3; Tuesday, January 27; 5 minutes; 5 points [Solutions follow on next page]

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

Lecture 3. Functions & Modules

Iterators & Generators

Lecture 18: Using Classes Effectively (Chapter 16)

CSC 326H1F, Fall Programming Languages. What languages do you know? Instructor: Ali Juma. A survey of counted loops: FORTRAN

Please write your answers clearly and neatly we can t give you credit if we can t decipher what you ve written.

CMPS 182: Introduction to Database Management Systems. Instructor: David Martin TA: Avi Kaushik. Syllabus

61A LECTURE 1 FUNCTIONS, VALUES. Steven Tang and Eric Tzeng June 24, 2013

Computer Science 210: Data Structures


MSO Lecture 1. Wouter Swierstra (adapted by HP) September 11, 2017

a declaration of class name, and a class docstring

Lecture 1. Course Overview, Python Basics

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Lecture 21. Programming with Subclasses

Internet Web Technologies ITP 104 (2 Units)

Instructor: Craig Duckett. Lecture 03: Tuesday, April 3, 2018 SQL Sorting, Aggregates and Joining Tables

CS Homework 4 Lifeguard Employee Ranker. Due: Tuesday, June 3rd, before 11:55 PM Out of 100 points. Files to submit: 1. HW4.py.

CSC209. Software Tools and Systems Programming.

CS Prelim 2 Review Fall 2018

Intro. Classes & Inheritance

CS 1803 Pair Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 29th, before 6 PM Out of 100 points

Lecture 4. Defining Functions

CIT 590 Homework 5 HTML Resumes

You may not share any information or materials with classmates during the exam and you may not use any electronic devices.

Lecture 4. Defining Functions

CS 253: Intro to Systems Programming 1/21

Tips from the experts: How to waste a lot of time on this assignment

CS 240 Fall Mike Lam, Professor. Just-for-fun survey:

Programming Languages and Techniques (CIS120)

Lists, loops and decisions

Programming. Dr Ben Dudson University of York

Tips from the experts: How to waste a lot of time on this assignment

CS 2316 Individual Homework 4 Greedy Scheduler (Part I) Due: Wednesday, September 18th, before 11:55 PM Out of 100 points

The following content is provided under a Creative Commons license. Your support

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Copied from: on 3/1/2017

Introduction to Computer Systems

CIS192 Python Programming. Robert Rand. August 27, 2015

CSE : Python Programming. Packages (Tutorial, Section 6.4) Announcements. Today. Packages: Concretely. Packages: Overview

Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9

COMP-202 Unit 0: Course Details

CSC148-Section:L0301

Computer Science II CSci 1200 Sections 6-10 Week 3, Monday Lecture January 28, 2002 Functions, Structs and Multiple Files

CS 1110 Final Exam, May 2018

Introduction to Prof. Clarkson Fall Today s music: Prelude from Final Fantasy VII by Nobuo Uematsu (remastered by Sean Schafianski)

ICS 31 UC IRVINE. ############## YOUR UCINET #### K E Y #### ############## Second Midterm YOUR NAME YOUR STUDENT ID (8 DIGITS)

We'll dive right in with an example linked list. Our list will hold the values 1, 2, and 3.!

CS 3030 Scripting Languages Syllabus

CS Homework 10 p. 1. CS Homework 10

CS 1110 Prelim 2 November 14th, 2013

Transcription:

CSC148: Week 1 http://www.cdf.utoronto.ca/~csc148h/summer/ Sophia Huynh Summer 2018 1

Outline Introduction Object-Oriented Design 2

Your instructor Sophia Huynh Master's Student Undergrad was done at UofT as well (Specialist in CS)! First time teaching a course Feedback is important! Let me know what I mess up! 3

What is CSC148? If 108 was about "learning how to program" 148 is about "how to program 'well'" (sort of) Designing code/classes Exploring different data types Programming efficiently 4

Background needed for CSC148 A credit in CSC108 is ideal You should know: Control structures (if-statements, whileand for-loops) How to define functions Various types (lists, dictionaries, etc.) But maybe not in Python; that's fine! 5

Background needed for CSC148 If you're nervous about some of those topics: The course website has links to resources as refreshers. Ask me (office hours, Piazza, after class)! 6

Logistics Course website: www.cdf.utoronto.ca/~csc148h/summer/ Office hours: Thursdays @ 3-5 PM in BA3219 7

Piazza Use this for discussions Do not post code for anything that will be graded! If you need me to look at code: make a Private Post 8

Piazza I will not answer questions within the first 12 hours of it being posted! Answering and asking questions is good for your learning! Exceptions: Urgent questions or things students wouldn't be able to answer. I'll (usually) answer within 3 days 9

Course Structure Weekly "labs" (not for marks) Weekly exercises (16% total) Released on Thursdays, due the following Thursday at 11PM 2 Assignments (22% total) 2 Term tests (24% total) 1 Final exam (38%) - Need 40% to pass 10

Labs Handouts on the course website Monday 6-8PM are "lab" times Attendance is not mandatory Go there to ask your TA questions, work through material, etc. Keeps you up to speed with the course and gives you practice. 11

Exercises 1 week to do them 10 exercises in total Weighting: Highest Grade Lowest Grade 3% 3% 2% 2% 2% 2% 1% 1% 0% 0% 12

Exercises Do not plagiarise! They're worth like 2% each. It's not worth it. If you need help, just ask (TAs, on Piazza, office hours, etc.) The exercises are all new! Google won't help you too much. 13

Assignments 2 in total Highest worth 14% Lowest worth 8% A1 will be released around May 26 14

Assignments As always: don't plagiarise! There'll be plenty of office hours, labs, resources, etc. available to help you. 15

Midterm Tests 2 in total Highest worth 16% Lowest worth 8% T1 is on June 7th (during lecture time) 16

Read the syllabus! Ask me after class or on Piazza if you have questions about it! 17

Software Using Python (like in CSC108) Recommended IDE: PyCharm Lab 1 goes over installing it. You can use other things, but PyCharm makes installing libraries easier. It's also a bit more organized. 18

Software The projector in this room won't show PyCharm well, so no demo of it. Lab 1 will get you familiar with it (and the TAs will help you!) 19

Lectures Slides posted after class Rough "script" will also be posted Just a general idea of what I plan to say during class; I'm bad at ad-libbing! 20

Lectures I'll randomly call out people to answer questions! Left-side vs. Right-side You'll usually have a few minutes to discuss with people around you 21

Left-side Are you allowed to post assignment code on Piazza? 22

Left-side Answer: No! 23

Right-side What is the weight of your lowest exercise grade? 24

Right-side Answer: 0% 25

Lectures I'll keep track of the left-side vs. right-side score Just for fun. Probably. 26

How to do well Do labs, exercises, and assignments Write code! Practice makes perfect! Watching and reading can only help so much. If you need help: Come talk to us! Labs, office hours, Piazza, etc. Try to start your work early! 27

How to do well Need more practice beyond the labs and exercises? Let me know! I can always try to make more examples and practice questions! 28

Object-oriented Design 29

Representing a Student We know that students have: Names Student numbers 30

Representing a Student We could represent these with variables: name = "Sophia" student_number = 1234 31

Representing a Student We could represent these with variables: name = "Sophia" student_number = 1234 student = (name, student_number) We could represent a student using a tuple... 32

Write a Class! 33

What is a Class? Essentially like "types" You can write your own though! We've seen the str class, list class, etc. They have methods which operate on them (like functions)! 34

Methods "cat".upper() 35

Methods "cat".upper() type is str upper() affects "cat", which is an instance of a string. 36

A Function upper("cat") 37

A method of str str.upper("cat") 38

A method of str str.upper("cat") Give the type Pass a string in as an argument 39

Implementing a Student Name Student number 40

Implementing a Student class Student: 41

Implementing a Student class Student: def init (self): Python's way of specifying how to initialize a class. 42

Implementing a Student class Student: def init (self): self is required here, but we can add more parameters. 43

Implementing a Student class Student: def init (self, n, num): n = Name num = Student Number 44

Implementing a Student class Student: def init (self, n: str, num: int) -> None: Documentation! Add in the types for your parameters, and the return type of the method. 45

Aside: Type Annotations def f(param1: type, param2: type) -> ReturnType: """ (type, type) -> ReturnType """ @param param1 type: description @param param2 type: description 46

Aside: Type Annotations def f(param1: type, param2: type) -> ReturnType: """ (type, type) -> ReturnType """ I use this one! @param param1 type: description @param param2 type: description I don't care which style you use, as long as you document types somehow. 47

Implementing a Student class Student: def init (self, n: str, num: int) -> None: """ Initialize a new student with the name n and student number num. """ 48

Aside: Docstrings """ Initialize a new student with the name n and student number num. """ Mention the parameters of your method/function by name. 49

Implementing a Student def init (self, n: str, num: int) -> None: """ Initialize a new student with the name n and student number num. """ 50

Implementing a Student def init (self, n: str, num: int) -> None: """ Initialize a new student with the name n and student number num. """ self.name = n 51

Implementing a Student def init (self, n: str, num: int) -> None: """ Initialize a new student with the name n and student number num. """ self.name = n self.student_number = num 52

Implementing a Student Now we can use self.name and def init (self, self.student_number n: anywhere str, within the num: class to int) get at these -> None: values! """ Initialize a new student with the name n and student number num. """ self.name = n self.student_number = num 53

Implementing a Student def init (self, n: str, num: int) -> None: """ Initialize a new student with the name n and student number num. """ self.name Descriptive = n parameter self.student_number names are better! = num 54

Implementing a Student def init (self, name: str, student_number: int) -> None: """ Initialize a new student with the name name and student number student_number. """ self.name = name self.student_number = student_number 55

Making an Instance of a Student How do we create a Student? 56

Making an Instance of a Student Need a variable to hold it. s = 57

Making an Instance of a Student Put in the class name. s = Student 58

Making an Instance of a Student Pass in the parameters (aside from self) s = Student("Sophia", 1234) 59

Making an Instance of a Student Pass in the parameters (aside from self) s = Student("Sophia", 1234) def init (self, name: str, student_number: int) -> None: 60

Making an Instance of a Student s = Student("Sophia", 1234) This is called our Constructor. It constructs a Student for us by calling init! 61

Using attributes of our Student s = Student("Sophia", 1234) s.name # Gives us 'Sophia' s.student_number # 1234 62

Using attributes of our Student def init (self, name: str, student_number: int) -> None: Lets us refer to the instance itself (otherwise, it has no name attached to it)! self.name = name self.student_number = student_number 63

Creating Students s2 = Student("David", 2345) s3 = Student("Danny", 1024) 64

Creating Students s2 = Student("David", 2345) s3 = Student("Danny", 1024) s2.name # 'David' s2.student_number #2345 s3.name # 'Danny' s3.student_number #1024 65

Creating Students s2 = Student("David", 2345) s3 = Student("Danny", 1024) s2.name # 'David' s2.student_number #2345 s3.name # 'Danny' s3.student_number #1024 Super readable! 66

Creating Students # Change the name of s3 s3.name = "Jen" s3.name # will now give us 'Jen' 67

Class vs Tuples s = ("Sophia", 1234) s[0] S[1] 68

Class vs Tuples s = ("Sophia", 1234) s[0] S[1] What if we had 20 attributes? 69

Class vs Dictionary s = {'name': 'Sophia', 'Student_number': 1234} s['name'] s['student_number'] 70

Class vs Dictionary s = {'name': 'Sophia', 'Student_number': 1234} s['name'] s['student_number'] tedious. It'll get ugly fast if we have a lot of attributes. It's also 71

Writing Methods Similar to writing functions Within a class Takes self as a parameter 72

Method 'enroll' Students can enroll in a course. 73

Method 'enroll' class Student: # omitted init def enroll(self, course: str) -> None: 74

Method 'enroll' class Student: # omitted init def enroll(self, course: str) -> None: Need an attribute to keep track of our courses! Go back to init! 75

Method 'enroll' def init (self, name: str, student_number: int) -> None: A student starts with an empty list of courses. """ Initialize a new student with the name name and student number student_number. """ self.name = name self.student_number = student_number self.courses = [] 76

Method 'enroll' class Student: # omitted init def enroll(self, course: str) -> None: """ Add course to this student's list of courses. """ self.courses 77

Method 'enroll' class Student: # omitted init def enroll(self, course: str) -> None: """ Add course to this student's list of courses. """ self.courses.append(course) 78

Using 'enroll' s = Student("Sophia", 1234) s.enroll("csc148") 79

Using 'enroll' s = Student("Sophia", 1234) s.enroll("csc148") s.courses # ['CSC148'] 80

Printing Students We want to be able to do this: >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> print(s) Sophia (1234) Enrolled in: CSC148 81

Printing Students Currently, we get this: >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> print(s) < main.student object at 0x1037686a0> 82

Printing Students Currently, we get this: >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> print(s) Memory Address! < main.student object at 0x1037686a0> Python's default: Type and 83

str method def str (self) -> str: """ Return the string version of this Student. >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> print(s) Sophia (1234) Enrolled in: CSC148 """ 84

str method def str (self) -> str: """ (omitted docstring) """ courses = ", ".join(self.courses) Get the courses, joined together by a comma and space. 85

str method def str (self) -> str: """ (omitted docstring) """ courses = ", ".join(self.courses) s = "{} ({})\nenrolled in: {}".format(self.name, self.student_number, courses) 86

Aside: str format s = "{} ({})\nenrolled in: {}".format(self.name, self.student_number, courses) s = self.name + " (" + str(self.student_number) +... 87

Aside: str format s = "{} ({})\nenrolled in: {}".format(self.name, self.student_number, courses).format() converts things to strings for us and replaces {} with the arguments passed in. s = self.name + " (" + str(self.student_number) +... 88

str method def str (self) -> str: courses = ", ".join(self.courses) s = "{} ({})\nenrolled in: {}".format(self.name, self.student_number, courses) return s 89

str method Now we get this: >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> print(s) Sophia (1234) Enrolled in: CSC148 90

Comparing Students Suppose we want to know if two students are the same or not Criteria: Students are the same if they have the same student number. 91

Comparing Students >>> s1 = Student('Jekyll', 101) >>> s2 = Student('Hyde', 101) 92

Comparing Students What we want: >>> s1 = Student('Jekyll', 101) >>> s2 = Student('Hyde', 101) >>> s1 == s2 True 93

Comparing Students What we get currently: >>> s1 = Student('Jekyll', 101) >>> s2 = Student('Hyde', 101) >>> s1 == s2 False 94

Comparing Students What we get currently: >>> s1 = Student('Jekyll', 101) >>> s2 = Student('Hyde', 101) >>> s1 == s2 False Python's default: Comparing the memory addresses of s1 and s2. 95

eq method def eq (self, other: object) -> bool: """ Return True if self and other are both Students with the same student number. >>> s1 = Student('Jekyll', 101) >>> s2 = Student('Hyde', 101) >>> s1 == s2 True """ 96

eq method def eq (self, other: object) -> bool: """ (omitted docstring) """ # Compare the types 97

eq method def eq (self, other: object) -> bool: if not isinstance(other, Student): return False 98

eq method def eq (self, other: object) -> bool: if type(other)!= Student: return False 99

eq method def eq (self, other: object) -> bool: if type(other)!= Student: return False isinstance() generalizes a bit better! 100

eq method def eq (self, other: object) -> bool: if not isinstance(other, Student): return False 101

eq method def eq (self, other: object) -> bool: if not isinstance(other, Student): return False if self.student_number == other.student_number: return True return False 102

eq method def eq (self, This other: comparison object) already -> bool: gives us True or False! if not isinstance(other, Student): return False return self.student_number == other.student_number 103

eq method def eq (self, other: object) -> bool: if not isinstance(other, Student): This format is preferred! return False return self.student_number == other.student_number 104

Left-side What is the method header to override how Python converts a class into a string? a) def str() -> str: b) def str () -> str: c) def str(self) -> str: d) def str (self) -> str: 105

Left-side Answer: d) def str (self) -> str: 106

Right-side What is the body of this init? def init (self, uni_name: str): a) uni_name = self.university_name b) self.university_name = uni_name c) university_name = uni_name d) uni_name = university_name 107

Right-side Answer: b) self.university_name = uni_name 108

More on Methods But first Maybe a 10 minute break? 109

Methods init enroll str eq 110

Methods init enroll str eq These methods are in all classes. We overrode Python's default behaviour when implementing them. 111

Magic Methods Surrounded by 2 underscores on both sides Methods that Python uses for its operators/builtins 112

Magic Methods init, str, and eq are the ones you'll see most often. repr comes up sometimes. Might not need to implement it, but it is useful. 113

repr If we try to look at s, we get: >>> s = Student('Sophia', 1234) >>> s < main.student object at 0x1037686a0> 114

repr If we try to look at s, we get: >>> s = Student('Sophia', 1234) >>> lst = [s] >>> print(lst) [< main.student object at 0x1037686a0>] 115

repr If we try to look at s, we get: >>> s = Student('Sophia', 1234) >>> lst = [s] >>> print(lst) [< main.student object at 0x1037686a0>] Python represents our class with a memory address and type. 116

repr So maybe we want: >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> s Sophia - 1234 - ['CSC148'] 117

repr def repr (self) -> str: """ Return a representation of this Student. >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> s Sophia - 1234 - ['CSC148']""" 118

repr def repr (self) -> str: """ Return a representation of this Student. >>> s = Student('Sophia', 1234) >>> s.enroll('csc148') >>> s Sophia - 1234 - ['CSC148']""" return "{} - {} - {}".format(self.name, self.student_number, self.courses) 119

Interlude: self str.upper("cat") 120

Interlude: self s = Student('Sophia', 1234) Student.enroll(s, "CSC148") 121

Interlude: self s = Student('Sophia', 1234) Student.enroll(s, "CSC148") There are 2 parameters! 122

Interlude: self s = Student('Sophia', 1234) Student.enroll(s, "CSC148") def enroll(self, course: str) -> None: self.courses.append(course) 123

Interlude: self s = Student('Sophia', 1234) Student.enroll(s, "CSC148") class Student:... def enroll(self, course: str) -> None: 124

Interlude: Documentation Document the types of all parameters Include a docstring describing what your method does Mention parameters by name Include 1~2 docstring examples Shows how your method should be called, and what it should return/do 125

Interlude: Documentation For classes: Include a class docstring Briefly describes your class Describe the attributes of your class Inside of the class: Add type annotations for its attributes 126

Interlude: Documentation For classes: Include a class docstring Briefly describes your class Describe the attributes of your class Inside of the class: Add type annotations for its attributes 127

Interlude: Documentation class Student: """ A class representing a Student. name - The name of the Student student_number - The student number of the Student """ name: str student_number: int 128

Interlude: Documentation At the start of your file/module, include a module docstring Short docstring that says what's in your file 129

Interlude: Documentation Documentation is important in practice Tedious, but comes naturally with practice Appreciate well documented code! What if people never documented things like list.extend, str.isalpha, etc.? :( 130

Designing a Class When do you want to write a class? If you have to write a class: What attributes should you have? What methods? 131

Designing a Class Sometimes it's obvious: Not a simple structure Contains some information Behaves in a certain way Can't represent it nicely with basic types 132

Designing a Class Usually given a description or a problem. Need to determine what classes are needed 133

Designing a Class: Example We want to keep track of an event's details. An event has a day, month, and a year (the date on which it occurs), as well as a description. An event is able to move to another date, and can tell when it conflicts with another event. 134

Designing a Class: Example Event class! We want to keep track of an event's details. An event has a day, month, and a year (the date on which it occurs), as well as a description. An event is able to move to another date, and can tell when it conflicts with another event. 135

Identifying Attributes If our class has something, it's probably an attribute E.g. A Student has a name, it has a student number, and it has courses. 136

Identifying Attributes We want to keep track of an event's details. An event has a day, month, and a year (the date on which it occurs), as well as a description. An event is Attributes able to move to another date, and can tell Day, when month, it conflicts year, with another event. description 137

Identifying Attributes We want to keep track of an event's details. An event has a day, month, and a year (the date on which it occurs), as well as a description. A date has a day, month, and An event is year! able to move to another date, and can tell when it conflicts with another event. We could have a Date class! But we won't. That's next week. 138

Identifying Attributes We want to keep track of an event's details. An event has a day, month, and a year (the date on which it occurs), as well as a description. An event is able to move to another date, and can tell when it conflicts with another event. 139

Identifying Methods Methods are usually actions (verbs) If a class can do something, then that something might be a method E.g. A Student can enroll in a course. 140

Identifying Methods Methods We want to keep track of an event's Changing details. dates An event has a day, month, and Telling a year when (the it date on which it occurs), as conflicts well as a with another event. description. An event is able to move to another date, and can tell when it conflicts with another event. 141

Method Design change_date Takes in a new date to move to Modifies the event's date conflicts_with Takes in another event to compare with Returns whether it conflicts or not 142

Implementing Event class Event: 143

Implementing Event class Event: def init (self, day, month, year, desc): 144

Implementing Event class Event: def init (self, day, month, year, desc): self.day = day self.month = month self.year = year self.description = desc 145

Implementing Event class Event:... def change_date(self, new_day, new_month, new_year): self.day = new_day self.month = new_month self.year = new_year 146

Implementing Event class Event:... def conflicts_with(self, other): return (self.day == other.day and self.month == other.month and self.year == other.year) 147

Designing from Client Code Given code that uses a class Know what methods take in and what they should return Internal workings are a mystery "As long as it works properly, it's okay." 148

Example: Restaurant Menu You are given the usage: >>> r = RestaurantMenu() >>> r.add_item("baguette", 3.50) >>> r.add_item("pizza", 5.50) >>> r.add_item("cola', 2.00) >>> r.get_price("baguette") 3.50 >>> r.get_below(4) ["Baguette", "Cola"] 149

Example: Restaurant Menu Often this will be in the main block or unittests like: if name == ' main ': r = RestaurantMenu() r.add_item("baguette", 3.50) r.add_item("pizza", 5.50) r.add_item("cola', 2.00) assert r.get_price("baguette") == 3.50 assert r.get_below(4) ==["Baguette", "Cola"] 150

Example: Restaurant Menu Often this will be in the main block or unittests like: This is called Client Code! Code that uses your class. if name == ' main ': r = RestaurantMenu() r.add_item("baguette", 3.50) r.add_item("pizza", 5.50) r.add_item("cola', 2.00) assert r.get_price("baguette") == 3.50 assert r.get_below(4) ==["Baguette", "Cola"] 151

Example: Restaurant Menu How do we want to represent our items? Could use a list of tuples Tuples in the form (item name, price) Could use a dictionary Key = Item name Value = price 152

Example: Restaurant Menu How do we want to represent our items? Could use a list of tuples Dictionaries are easier for this, so let's use that. Tuples in the form (item name, price) Could use a dictionary Key = Item name Value = price 153

Example: Restaurant Menu class RestaurantMenu: 154

Example: Restaurant Menu class RestaurantMenu: def init (self): self.items = {} 155

Example: Restaurant Menu class RestaurantMenu: def init (self): self.items = {} def add_item(self, item, price): self.items[item] = price 156

Example: Restaurant Menu class RestaurantMenu:... def get_price(self, item): return self.items[item] 157

Example: Restaurant Menu def get_below(self, price): items_below = [] for item in self.items: 158

Example: Restaurant Menu def get_below(self, price): items_below = [] for item in self.items: if self.items[item] < price: items_below.append(item) 159

Example: Restaurant Menu def get_below(self, price): items_below = [] for item in self.items: if self.items[item] < price: items_below.append(item) items_below.sort() 160

Example: Restaurant Menu def get_below(self, price): items_below = [] for item in self.items: if self.items[item] < price: items_below.append(item) items_below.sort() return items_below 161

Things to consider Lots of cases: E.g. "What happens if get_price is given an item that wasn't added"? Could raise an error or return -1 If not specified, it's up to you Maybe have a precondition to assume that won't happen For assignments/exercises: Ask! 162

Homework Read the syllabus! Lab 1 Install Pycharm and get familiar with it Practice in class design Getting used to PythonTA Exercise 1 (due next Thursday @ 11PM) 163