CSC148 Intro. to Computer Science

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

Welcome to CSC148! Introduction to Computer Science

CSC148 Intro. to Computer Science

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

CSC148-Section:L0301

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

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

Last week. Last week. Last week. Today. Binary Trees. CSC148 Intro. to Computer Science. Lecture 8: Binary Trees, BST

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

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

CSC148 Recipe for Designing Classes

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

Lecture 19. Operators and Abstraction

CS1004: Intro to CS in Java, Spring 2005

Object Oriented Programming

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

Topic 7: Algebraic Data Types

Object Oriented Programming

OBJECT ORIENTED PROGRAMMING

Working with classes and objects COSC346

ITI Introduction to Computing II

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

COMPSCI 105 S Principles of Computer Science. Classes 3

CSC148: Week 1

Lecture 19. Using Classes Effectively

PREPARING FOR THE FINAL EXAM

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

ITI Introduction to Computing II

Programming I. Course 9 Introduction to programming

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

PREPARING FOR PRELIM 1

CS108 Lecture 16: User Defined Classes. Overview/Questions

PREPARING FOR PRELIM 2

Java Object Oriented Design. CSC207 Fall 2014

CSC148-Section:L0301

Lecture #14: OOP. Last modified: Mon Feb 27 15:56: CS61A: Lecture #14 1

Algorithms and Programming

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

Introduction to Programming: Lecture 10

Anatomy of a Method. HW3 is due Today. September 15, Midterm 1. Quick review of last lecture. Encapsulation. Encapsulation

Computational Mathematics with Python

CSC148 Intro. to Computer Science

MechEng SE3 Lecture 7 Domain Modelling

Lecture #1. Introduction to Classes and Objects

CS112 Lecture: Defining Instantiable Classes

Why efficiency of algorithm matters? CSC148 Intro. to Computer Science. Comparison of growth of functions. Why efficiency of algorithm matters?

CSC102 INTRO TO PROGRAMMING WITH PYTHON REVIEW MICHAEL GROSSBERG

CSI33 Data Structures

CS 320 Introduction to Software Engineering Spring March 06, 2017

Control Structures. CIS 118 Intro to LINUX

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

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

CSC324 Principles of Programming Languages

What We ll Be Seeing Today

Introduction Programming Using Python Lecture 8. Dr. Zhang COSC 1437 Fall 2017 Nov 30, 2017

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

CMSC201 Computer Science I for Majors

CMPT 117: Tutorial 1. Craig Thompson. 12 January 2009

Cmpt 135 Assignment 2: Solutions and Marking Rubric Feb 22 nd 2016 Due: Mar 4th 11:59pm

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5'

Informatics 1 Functional Programming Lecture 9. Algebraic Data Types. Don Sannella University of Edinburgh

Fast Introduction to Object Oriented Programming and C++

Test #2 October 8, 2015

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

Computational Physics

CS304 Object Oriented Programming Final Term

Chapter 4: Writing Classes

Circle all of the following which would make sense as the function prototype.

Introduction to Programming Using Python Lecture 4. Dr. Zhang COSC 1437 Fall, 2018 October 11, 2018

Use the scantron sheet to enter the answer to questions (pages 1-6)

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

Introduction to Classes and Objects. David Greenstein Monta Vista High School

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

Data Structures (list, dictionary, tuples, sets, strings)

Assignment 2. CS 234 Fall 2018 Sandy Graham. Create()

Object Oriented Programming 2015/16. Final Exam June 28, 2016

Exceptions. raise type(message) raise Exception(message)

Inductive Data Types

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Review 2. Classes and Subclasses

CS 320: Concepts of Programming Languages

CSC148: Week 2

Outline. Outline. 1 Chapter 2: Data Abstraction

Principles of Object Oriented Programming. Lecture 4

CS-202 Introduction to Object Oriented Programming

Lecture 18: Using Classes Effectively (Chapter 16)

CSI33 Data Structures

Lecture 18. Methods and Operations

CSC326 Object Oriented Programming i. CSC326 Object Oriented Programming

MITOCW watch?v=flgjisf3l78

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

a declaration of class name, and a class docstring

CS 520 Theory and Practice of Software Engineering Fall 2017

Exceptions. raise type(message) raise Exception(message)

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

More C++ : Vectors, Classes, Inheritance, Templates

CS1150 Principles of Computer Science Objects and Classes

Transcription:

CSC148 Intro. to Computer Science Lecture 2: designing classes, special methods, managing attributes; intro composition, inheritance Amir H. Chinaei, Summer 2016 Office Hours: R 10 12 BA4222 csc148ta@cdf.toronto.edu http://web.cs.toronto.edu/program/ugrad/ug_helpcentre.htm ahchinaei@cs.toronto.edu http://www.cs.toronto.edu/~ahchinaei/ Course page: http://www.cs.toronto.edu/~ahchinaei/teaching/20165/csc148/ Designing Classes 2-1

Recall Read the course Info Sheet, carefully Lab01 Issues not know/remember CDF account working on laptops instead not worked in teams of 2 not prepared for lab01 discussion Refer to the course page for instructions, handouts, and links to read Do these, prior to go to the lab Designing Classes 2-2

Recall Use all resources available to you Before it becomes too late! What resources? Office Hours: R 10-12 BA4222 The course web page and its many hyperlinks! The CS Help Centre The course forum The TAs mailing list: csc148ta @ cdf.toronto.edu Email ahchinaei @ cs.torotno.edu Note: On May 26, the Bahen building is among some other buildings that will be closed from ~9pm to May 27, due to a power turn-off. It will NOT affect our lecture though. Designing Classes 2-3

Review So far Recap of basic Python refer to ramp_up slides in the course web page Introduction to object oriented design In particular, defining new compound data types ~ classes Examples: Class Rectangle, Class Point Today Special methods Manage attributes Introduction to composition and inheritance Designing Classes 2-4

Key terms Class: (abstract/advanced/compound) data type It models a thing or concept (let s call it object), based on its common (or important) attributes and actions in a specific project In other words, it bundles together attributes and methods that are relevant to each instance of those objects In OO world, objects are often active agents In other words, actions are invoked on objects E.g. you invoke an action on your phone to dial a number E.g. you invoke an action on your alarm to wake you up E.g. you invoke an action on your fridge to get you ice Designing Classes 2-5

Design roadmap--step 1 Before Start!: Read the project specification carefully In the specification: frequent nouns may be good candidate for classes properties of such nouns may be good candidates for attributes actions of such nouns may be good candidates for methods Keep in mind, that there are some special methods that are relevant to many classes Designing Classes 2-6

Point class (revisited) Specification: discussion In two dimensions, a point is two numbers (coordinates) that are treated collectively as a single object. Points are often written in parentheses with a comma separating the coordinates. For example, (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. Some of the typical operations that one associates with points might be calculating the distance of a point from the origin, or from another point, or finding a midpoint of two points, or asking if a point falls within a given rectangle or circle. Designing Classes 2-7

Point class (revisited) Specification: In two dimensions, a point is two numbers (coordinates) that are treated collectively as a single object. Points are often written in parentheses with a comma separating the coordinates. For example, (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. Some of the typical operations that one associates with points might be calculating the distance of a point from the origin, or from another point, or finding a midpoint of two points, or asking if a point falls within a given rectangle or circle. Designing Classes 2-8

Point class (revisited) Specification: In two dimensions, a point is two numbers (coordinates) that are treated collectively as a single object. Points are often written in parentheses with a comma separating the coordinates. For example, (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. Some of the typical operations that one associates with points might be calculating the distance of a point from the origin, or from another point, or finding a midpoint of two points, or asking if a point falls within a given rectangle or circle. Designing Classes 2-9

Point class (revisited) Specification: In two dimensions, a point is two numbers (coordinates) that are treated collectively as a single object. Points are often written in parentheses with a comma separating the coordinates. For example, (0, 0) represents the origin, and (x, y) represents the point x units to the right and y units up from the origin. Some of the typical operations that one associates with points might be calculating the distance of a point from the origin, or from another point, or finding a midpoint of two points, or asking if a point falls within a given rectangle or circle. Designing Classes 2-10

Design roadmap--step 2 Now, we can define a class API: 1. choose a class name and write a brief description in the class docstring 2. write some examples of client code that uses your class 3. decide what services your class should provide as public methods, for each method declare an API (header, type contract, examples, description) refer to function design recipe 4. decide which attributes your class should provide without calling a method, list them in the class docstring Designing Classes 2-11

discussion Let s do it in PyCharm Designing Classes 2-12

Design roadmap--step 3 Then, implement the class: 1. body of special methods, init, eq, str 2. body of other methods e.g. distance 3. testing (more on this later) Designing Classes 2-13

discussion Let s do it in PyCharm Designing Classes 2-14

Rectangle class (revisit) A rectangle can be defined in many different ways. Here, assume a rectangle is defined by its top-left coordinates as well as its width and height. A rectangle is usually represented by a quadruple (x, y, w, h) where x and y represent the top-left coordinate, w represents the width, and h represents the height. For example, (10, 20, 300, 400) represents a rectangle that its top-left coordinate is located at point (10,20), its width is 300 and its height is 400. Some of the typical operations that one associates with rectangles might be translating the rectangle to the right, left, up, and down, or asking if two rectangles are conceptually equal, which means have same coordinate and size, or asking if a rectangle falls within another rectangle, etc. Designing Classes 2-15

Rectangle class (revisit) A rectangle can be defined in many different ways. Here, assume a rectangle is defined by its top-left coordinates as well as its width and height. A rectangle is usually represented by a quadruple (x, y, w, h) where x and y represent the top-left coordinate, w represents the width, and h represents the height. For example, (10, 20, 300, 400) represents a rectangle that its top-left coordinate is located at point (10,20), its width is 300 and its height is 400. Some of the typical operations that one associates with rectangles might be translating the rectangle to the right, left, up, and down, or asking if two rectangles are conceptually equal, which means have same coordinate and size, or asking if a rectangle falls within another rectangle, etc. Designing Classes 2-16

Rational class Rational numbers are ratios of two integers p/q, where p is called the numerator and q is called the denominator. The denominator q is non-zero. Operations on rationals include addition, multiplication, and comparisons: <> < > = Designing Classes 2-17

Recall: design roadmap Step 1: Read the project specification carefully Rational numbers are ratios of two integers p/q, where p is called the numerator and q is called the denominator. The denominator q is non-zero. Operations on rationals include addition, multiplication, and comparisons: <> < > = Note: Python provides special methods: ne lt le gt ge eq Other special methods: init str add mul Designing Classes 2-18

Recall: design roadmap Step 2: Define a class API: 1. choose a class name and write a brief description in the class docstring 2. write some examples of client code that uses your class 3. decide what services your class should provide as public methods, for each method declare an API (header, type contract, examples, description) refer to function design recipe 4. decide which attributes your class should provide without calling a method, list them in the class docstring Designing Classes 2-19

API: class definition & constructor class Rational: A rational number discussion def init (self, num, denom=1): Create new Rational self with numerator num and denominator denom --- denom must not be 0. :type self: Rational :type num: int :type denom: int :rtype: None pass Designing Classes 2-20

API: other methods (==) def eq (self, other): Return whether Rational self is equivalent to other. :type self: Rational :type other: Rational Any :rtype: bool >>> r1 = Rational(3, 5) >>> r2 = Rational(6, 10) >>> r3 = Rational(4, 7) >>> r1 == r2 True >>> r1. eq (r3) False pass discussion Designing Classes 2-21

API: other methods (str()) def str (self): Return a user-friendly string representation of Rational self. :type self: Rational :rtype: str >>> print(rational(3, 5)) 3 / 5 pass discussion Designing Classes 2-22

API: other methods (<) def lt (self, other): Return whether Rational self is less than other. :type self: Rational :type other: Rational Any :rtype: bool >>> Rational(3, 5). lt (Rational(4, 7)) False >>> Rational(3, 5). lt (Rational(5, 7)) True pass discussion Designing Classes 2-23

API: other methods (*) def mul (self, other): Return the product of Rational self and Rational other. :type self: Rational :type other: Rational :rtype: Rational discussion >>> print(rational(3, 5). mul (Rational(4, 7))) 12 / 35 pass Designing Classes 2-24

API: other methods (+) def add (self, other): Return the sum of Rational self and Rational other. :type self: Rational :type other: Rational :rtype: Rational discussion >>> print(rational(3, 5). add (Rational(4, 7))) 41 / 35 pass Designing Classes 2-25

design roadmap Continue to develop API for all other methods Then, Step 3: Develop the implementation Designing Classes 2-26

imp: class definition & constructor class Rational: A rational number def init (self, num, denom=1): Create new Rational self with numerator num and denominator denom --- denom must not be 0. :type self: Rational :type num: int :type denom: int :rtype: None self.num, self.denom = int(num), int(denom) Designing Classes 2-27

imp: other methods (==) def eq (self, other): Return whether Rational self is equivalent to other. :type self: Rational :type other: Rational Any :rtype: bool >>> r1 = Rational(3, 5) >>> r2 = Rational(6, 10) >>> r3 = Rational(4, 7) >>> r1 == r2 True >>> r1. eq (r3) False return (type(self) == type(other) and self.num * other.denom == self.denom * other.num) Designing Classes 2-28

imp: other methods (str()) def str (self): Return a user-friendly string representation of Rational self. :type self: Rational :rtype: str >>> print(rational(3, 5)) 3 / 5 return "{} / {}".format(self.num, self.denom) Designing Classes 2-29

imp: other methods (<) def lt (self, other): Return whether Rational self is less than other. :type self: Rational :type other: Rational Any :rtype: bool >>> Rational(3, 5). lt (Rational(4, 7)) False >>> Rational(3, 5). lt (Rational(5, 7)) True return self.num * other.denom < self.denom * other.num Designing Classes 2-30

imp: other methods (*) def mul (self, other): Return the product of Rational self and Rational other. :type self: Rational :type other: Rational :rtype: Rational >>> print(rational(3, 5). mul (Rational(4, 7))) 12 / 35 return Rational(self.num * other.num, self.denom * other.denom) Designing Classes 2-31

imp: other methods (+) def add (self, other): Return the sum of Rational self and Rational other. :type self: Rational :type other: Rational :rtype: Rational >>> print(rational(3, 5). add (Rational(4, 7))) 41 / 35 return Rational(self.num * other.denom + other.num * self.denom, self.denom * other.denom) Designing Classes 2-32

What if the denominator is 0? Designing Classes 2-33

Encapsulation Hiding instance attributes from clients by making them private Pythonic way of thinking of attributes is to leave them public However, if you wish, you can make them private by using Getters, Setters, and Properties Designing Classes 2-34

Getters, setters, and properties def _get_num(self): # # Return numerator num. # # :type self: Rational # :rtype: int # # >>> Rational(3, 4)._get_num() # 3 # return self._num Designing Classes 2-35

Getters, setters, and properties def _set_num(self, num): # # Set numerator of Rational self to num. # # :type self: Rational # :type num: int # :rtype: None # self._num = int(num) num = property(_get_num, _set_num) Designing Classes 2-36

Getters, setters, and properties def _get_denom(self): # # Return denominator of Rational self. # # :type self: Rational # :rtype: int # # >>> Rational(3, 4)._get_denom() # 4 # return self._denom Designing Classes 2-37

Getters, setters, and properties def _set_denom(self, denom): # # Set denominator of Rational self to denom. # # :type self: Rational # :type denom: int # :rtype: None # if denom == 0: raise Exception("Zero denominator!") else: self._denom = int(denom) denom = property(_get_denom, _set_denom) Designing Classes 2-38

OOP Features Composition and Inheritance A rectangle has some vertices (points) A triangle has some vertices (points) A triangle is a shape A rectangle is a shape has_a vs is_a relationship a shape has a perimeter A rectangle can inherit the perimeter from a shape A triangle too a shape has an area Can be area of a rectangle or triangle abstracted to the shape level? Designing Classes 2-39