CSC148 Recipe for Designing Classes

Similar documents
Question 1. CSC 120H1 F Midterm Test Solutions Fall 2017

CSC148 Intro. to Computer Science

Lecture 17: Classes (Chapter 15)

CSCA08 Winter 2018 Week 3: Logical Operations, Design Recipe. Marzieh Ahmadzadeh, Brian Harrington University of Toronto Scarborough

Lecture 18: Using Classes Effectively (Chapter 16)

CSC148: Week 1

Write for your audience

Lecture 17: Classes (Chapter 15)

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

Objects. say something to express one's disapproval of or disagreement with something.

PREPARING FOR PRELIM 1

Welcome to CSC148! Introduction to Computer Science

7. (2 pts) str( str( b ) ) str '4' will not compile (single, double, or triple quotes

CS 1110 Prelim 2 November 6th, 2012

CS 1110 Prelim 2 Solutions April 2018

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

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

Lecture 19. Operators and Abstraction

CSC148-Section:L0301

: Intro Programming for Scientists and Engineers Assignment 7: Classes

Assertions, pre/postconditions

Lecture 21. Programming with Subclasses

Do not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully.

Lecture 4. Defining Functions

CS 1110 Prelim 2 November 14th, 2013

Lecture 19. Using Classes Effectively

UTORid: Lecture Section: (circle one): L0101 (MWF10) L0201 (MWF11) Instructor: Jacqueline Smith Jen Campbell

class objects instances Fields Constructors Methods static

UNIVERSITY OF TORONTO SCARBOROUGH. Fall 2015 EXAMINATIONS. CSC A20H Duration 3 hours. No Aids Allowed

1 Docstrings. COSC 101 Lecture #14 Handout: Defining Functions, Part 4 Spring 2015

PREPARING FOR PRELIM 2

Question 0. Do not turn this page until you have received the signal to start.

Lecture 18. Using Classes Effectively

CSC148, Lab #4. General rules. Overview. Tracing recursion. Greatest Common Denominator GCD

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

CS 1110 Final Exam May 9th, 2013 SOLUTIONS

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Lecture 21. Programming with Subclasses

Abstract Data Types Chapter 1

Overview of List Syntax

CS Prelim 2 Review Fall 2018

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

CS115 - Module 4 - Compound data: structures

Lecture 6: Specifications & Testing

Flow Control: Branches and loops

Module 5: Lists. Readings: HtDP, Sections 9, 10.

Do not turn this page until you have received the signal to start. In the meantime, please read the instructions below carefully.

In addition to the correct answer, you MUST show all your work in order to receive full credit.

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

: Intro Programming for Scientists and Engineers Final Exam

Lecture 4. Defining Functions

CS 111X - Spring Final Exam - KEY

CSC148: Week 2

61A Lecture 3. Friday, September 5

USING DRUPAL. Hampshire College Website Editors Guide

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

ACORN.COM CS 1110 SPRING 2012: ASSIGNMENT A1

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

CS 1110 Prelim 1 October 4th, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

EXAMINATION INSTRUCTIONS

CIS220 In Class/Lab 1: Due Sunday night at midnight. Submit all files through Canvas (25 pts)

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Outline. Helper Functions and Reuse. Conditionals. Evaluation Rules for cond. Design Recipe with cond. Compound Data

CS Prelim 2 Review Fall 2017

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

CS 1110 Final Exam Solutions May 2018

a declaration of class name, and a class docstring

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Prelim 2 November 13th, 2014

CS 1110 Final Exam, May 2018

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

CS 2316 Exam 1 Practice ANSWER KEY

CS 1110 Final, May 2017

CSE 142/143 Unofficial Style Guide

Lecture 18. Methods and Operations

CMSC 201 Spring 2016 Lab 08 Strings and File I/O

CS 2316 Homework 9a GT Room Reservation Login

CSI33 Data Structures

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

CS 1110 Prelim 2 November 10th, 2016

Extending CircuitPython: An Introduction

CSCI 204 Introduction to Computer Science II

CSCI 200 Lab 1 Implementing and Testing Simple ADTs in Java

Lecture 4. Defining Functions

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

CS Prelim 2 Review Fall 2012

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

CS150 - Sample Final

Text Input and Conditionals

Computer Programming : C++

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Lecture 5. Defining Functions

CS 1110 Final, December 8th, Question Points Score Total: 100

Transcription:

Part 1: Define the API for the class CSC148 Recipe for Designing Classes Download the sample code here: https://www.teach.cs.toronto.edu/~csc148h/fall/lectures/object-oriented-programming/common/course. py. A summary can be found on the last page. 1. Class name and description. Pick a noun to be the name of the class, write a one-line summary of what that class represents, and (optionally) write a longer, more detailed description. These should help others quickly figure out what your class represents. class Course: A university course. In this case, there isn t much to say, since most everyone knows what a university course is. You may wonder why we don t explain what aspects of a course the class is going to model, but that will come at a later step. 2. Example. Write some simple examples of client code that uses your class. This will help you figure out what the API should be. By taking the point of view of the client, your design is likely to make the class convenient to use. Focus for now on standard cases (as opposed to a tricky or corner case.) You can put your code in a main block. Example: if name == main : csc148 = Course( csc148, 120, dict(a1=10, a2=10, t1=15, t2=15, final=50)) csc148.enrol( 123456789 ) csc148.enrol( 111111111 ) csc148.enrol( 888888888 ) csc148.record_grade( 123456789, a1, 86) csc148.record_grade( 123456789, final, 86) csc148.record_grade( 888888888, a1, 74) print(csc148.grade( 888888888, a1 )) print(csc148.course_grade( 123456789 )) print(csc148.class_average( a1 )) print(csc148) In order to come up with this code, many decisions had to be made. For example, we chose to specify an enrolment cap (in this example, it is 120) and had to come up with a way to specify the course marking scheme (we chose to use a dictionary). As we progress through the recipe, we may realize some decisions weren t great. That s fine; we can come back and revise. 3. Public methods. Using your example as a starting point, decide what services your class should provide for client code, i.e., what actions could be performed on instances of this class. For each of these actions, use the first four steps of the Function Design Recipe to define the interface for a method that will provide the action: (1) Example (2) Type Contract (3) Header (4) Description Since you are writing methods, not functions, don t forget to include self as the first parameter. You must define a constructor, init, and often will want to define str to generate a string representation of instances of the class, and eq to check whether two instances are equal. For brevity, only the constructor and one other method is shown below. You can see the rest in the full example code. def init (self, name: str, cap: int, scheme: Dict[str, int]) -> None: Initialize this course. Precondition: The sum of all values of <scheme> must equal 100. >>> c.name cscfun >>> c.cap 50 pass

def enrol(self, student_id: str) -> bool: Enrol a student in this course. Enrol the student with id <student_id> in this course, if there is room. Return whether enrolment was successful, i.e., this student was not already enrolled, and there was room for to enrol them. >>> c.enrol( 12345 ) >>> c.grade( 12345, exam ) is None pass 4. Public attributes. Decide what data you would like client code to be able to access without calling a method. This is not a clear-cut decision, since one could require all data to be accessed by calling a method (and in some languages, that is the convention). Python takes the oppositive point of view: treat attributes as public unless you have a good reason not to. Here are two situations when it makes sense to treat the attribute as private. In these cases, we expect the user to access the data by calling methods. An attribute with complex restrictions on its value. If client code were to assign a value to the attribute directly, it might inadvertently violate the restriction. If instead it is required to call a method to change the value, the method implementation can enforce any restriction. An attribute that represents data from the domain in a complex way. (We ll learn some fairly complex data structures this term.) By expecting client code to access the information through a method call, we spare the client code from having to be aware of the complex details, and we also avoid the problem of client code accidentally messing up important properties of the data structure. Once you have chosen the public attributes, add a section to your class docstring after the description, specifying the name and desecription of each of these attributes. Then below the docstring, specify the type of each variable as well. Use the format below. class Course: A university course. === Instance Attributes === name: the name of this course. cap: The enrolment cap for this course, i.e., the maximum number of students who may enrol. name: str cap: int At this point you have defined everything that client code needs in order to use the class successfully.

Part 2: Implement the class Now turn your attention to implementing the class. Any comments you write at this point concern implementation details, and are for the developers of the class itself. As a result, they will not go in the class docstring or in method docstrings; these are for developers of client code. 5. Internal (private) attributes. In order to write the bodies of the public methods, you will likely need additional attributes, but ones that the client code (a) need not know about and (b) should not access directly. For example, we need a way to record all the grades in the course. We chose a dictionary of dictionaries (organized first by student, then by course element), but client code shouldn t have to traverse this structure that s the job of your class. A programmer who writes client code shouldn t even have to know which structure you chose. In fact, if client code always accesses data through your public methods, you have the freedom to change internal details without breaking any client code. An internal attribute is not part of the public interface of the class, and its name should begin with an underscore to indicate this. Add a separate section to the class docstring for private attributes. For each internal attribute, use the same format as above to define the type, name, and description of each of the internal attributes.... === Private Attributes === _scheme: The marking scheme for this course. Each key is an element of the course, and its value is the weight of that element towards the course grade. _grades: The grades earned so far in this course. Each key is a student ID and its value is a dict mapping a course element to the student s mark on that element. If a student did not submit that element, it does not appear as a key in the student s dict. If, however, they earned a grade of zero, this is recorded as any other grade would be. name: str cap: int _scheme: Dict[str, int] _grades: Dict[str, Dict[str, int]] 6. Representation invariants. Add a section to your class docstring containing invariants that involve your attributes: things that must always be true (one could say they must never vary from truth, hence the name invariant ). These may be restrictions that cannot be captured by types alone in Python. For example, a student s age must be greater than 0, or every course code must consist of 3 letters and then 3 numbers. They may also express important relationships between the attributes.... === Representation Invariants === - The sum of all weights in _scheme must be 100. - Each key in every student s dict of grades must be an element of the course grading scheme, i.e., must occur as a key in _scheme. 7. Implement Public Methods. Use the last two steps of the function design recipe to implement the public methods in your class. (5) Code the Body (6) Test your Method Use helper methods to simplify your code. A helper method is not part of the public interface of the class, and its name should begin with an underscore to indicate this. For each method, you should assume that the representation invariants are all satisfied when the method is called, but you must ensure that the invariants are satisfied when the method exits. Note that your constructor should initialize all of the attributes of the instance; it should not do anything else. You can find the complete implementation in the full code example. def init (self, name: str, cap: int, scheme: Dict[str, int]) -> None: Initialize this course.

Precondition: The sum of all values of <scheme> must equal 100. >>> c.name cscfun >>> c.cap 50 self.name = name self.cap = cap self._scheme = scheme self._grades = {} def enrol(self, student_id: str) -> bool: Enrol a student in this course. Enrol the student with id <student_id> in this course, if there is room. Return whether enrolment was successful, i.e., this student was not already enrolled, and there was room for to enrol them. >>> c.enrol( 12345 ) >>> c.grade( 12345, exam ) is None if len(self._grades) < self.cap: if student_id in self._grades: return False else: self._grades[student_id] = {} return else: return False Notice that method init does not confirm that its precondition for parameter scheme is met. The same is true of other methods with preconditions. A method simply assumes that its preconditions are true, and makes no promises about what will happen if they are not.

Summary Part 1: Define the API for the class 1. Class name and description. Pick a noun to be the name of the class, write a one-line summary of what that class represents, and (optionally) write a longer, more detailed description. 2. Example. Write some simple examples of client code that uses your class. 3. Public methods. Decide what services your class should provide. For each, define the API for a method that will provide the action. Use the first four steps of the Function Design Recipe to do so: (1) Example (2) Type Contract (3) Header (4) Description 4. Public attributes. Decide what data you would like client code to be able to access without calling a method. Add a section to your class docstring after the longer description, specifying the type, name, and description of each of these attributes. Part 2: Implement the class 5. Internal attributes. Define the type, name, and description of each of the internal attributes. Put this in a separate section of the class docstring. 6. Representation invariants. Add a section to your class docstring containing any representation invariants. 7. Public methods. Use the last two steps of the function design recipe to implement all of the methods: (5) Code the Body (6) Test your Method