Announcements for This Lecture

Similar documents
Announcements for This Lecture

Lecture 17: Classes (Chapter 15)

Lecture 18. Methods and Operations

Lecture 17: Classes (Chapter 15)

Lecture 18. Using Classes Effectively

Announcements for the Class

Lecture 19. Operators and Abstraction

Announcements for this Lecture

Lecture 7. Memory in Python

CS 1110: Introduction to Computing Using Python Loop Invariants

Review 2. Classes and Subclasses

PREPARING FOR PRELIM 1

PREPARING FOR PRELIM 2

PREPARING FOR THE FINAL EXAM

CS 1110 Prelim 2 November 10th, 2016

Lecture 18: Using Classes Effectively (Chapter 16)

Lecture 18. Classes and Types

Lecture 20. Subclasses & Inheritance

CS 1110 Prelim 2 November 14th, 2013

CS Lecture 19: Loop invariants

Lecture 21. Programming with Subclasses

Lecture 9. Memory and Call Stacks

Readings for This Lecture

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

CS 1110 Prelim 2 November 13th, 2014

CS 1110 Prelim 2 November 12th, 2015

Lecture 21. Programming with Subclasses

CS Prelim 1 Review Fall 2018

PREPARING FOR THE FINAL EXAM

Lecture 21. Programming with Subclasses

CS 1110 Prelim 2 November 12th, 2015

CS Prelim 2 Review Fall 2018

Lecture 10. Memory in Python

Lecture 12. Lists (& Sequences)

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

CS Prelim 1 Review Fall 2013

CS Prelim 1 Review Fall 2017

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

Lecture 19: Subclasses & Inheritance (Chapter 18)

CS Prelim 1 Review Fall 2012

Iteration and For Loops

Lecture 24: Loop Invariants

CSC148-Section:L0301

CS 1110 Prelim 1 October 4th, 2012

Lecture 22. While Loops

Lecture 19. Using Classes Effectively

Lecture 5. Defining Functions

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

CS 1110 Prelim 1 October 15th, 2015

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce

CS Prelim 1 Review Fall 2016

Lecture 11: Iteration and For-Loops

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

Lecture 13. For-Loops

CS 1110 Prelim 2 Solutions April 2018

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

Object Oriented Programming in Python 3

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

ECS15, Lecture 13. Midterm solutions posted. Topic 4: Programming in Python, cont. Staying up to speed with Python RESOURCES. More Python Resources

isinstance and While Loops

CS 1110 Prelim 2 November 6th, 2012

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

CS Prelim 1 Review Fall 2013

CS Prelim 2 Review Fall 2012

Lecture 4. Defining Functions

Lecture 13. For-Loops

CS 1110 Prelim 1 October 17th, 2013

Lecture 14. Nested Lists and Dictionaries

CS Prelim 2 Review Fall 2015

OBJECT ORIENTED PROGRAMMING

CS Prelim 2 Review Fall 2014

Lecture 7: Objects (Chapter 15) CS 1110 Introduction to Computing Using Python

CS Prelim 2 Review Fall 2017

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Fundamentals: Expressions and Assignment

Lecture 13. Call Stacks & Debugging

Python Development with PyDev and Eclipse -

Lecture 2: Variables & Assignments

Lecture 4. Defining Functions

Conditionals & Control Flow

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

Assertions, pre/postconditions

CS108 Lecture 16: User Defined Classes. Overview/Questions

ASYMPTOTIC COMPLEXITY

Review 1. Call Frames; Diagramming Objects

Lecture 10: Lists and Sequences

CS 1110: Introduction to Computing Using Python Lists and Sequences

CSC148 Recipe for Designing Classes

Class Design (Section 9 of 17)

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Introduction to Programming

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

CS 1110 Final, December 16th, 2013

Lecture 4. Defining Functions

Variable and Data Type I

CS 11 python track: lecture 4

Introduction to Python

The Pyth Language. Administrivia

Transcription:

Lecture 17 Classes

Announcements for This Lecture Assignments A4 Thursday at midnight Hopefully you are on Task 4 Minor extension for reasons Will post A5 on Wednesday Written assignment like A2 Needs material from Tues Will post A6 on Friday Not due until November 14 Want to avoid exam crunch Lab this Week More prelim exercises This time for-loops Plus a simple class Exams Last week for regrades Limit them to valid issues Getting closer to prelim 2 2

Recall: Objects as Data in Folders An object is like a manila folder It contains other variables Variables are called attributes Can change values of an attribute (with assignment statements) It has a tab that identifies it Unique number assigned by Python Fixed for lifetime of the object Unique tab identifier id2 x 2.0 y 3.0 z 5.0 3

Recall: Classes are Types for Objects Values must have a type An object is a value Object type is a class id2 Classes are how we add new types to Python Types x 2.0 y 3.0 z 5.0 class name int float bool str Classes RGB Turtle Window 4

Recall: Classes are Types for Objects Values must have a type An object is a value Object type is a class id2 x 2.0 y 3.0 z 5.0 class name Classes are how we add new types to Python int float bool str Types But in Python3, type and class are now both synonyms Classes RGB Turtle Window 5

Classes Have Folders Too Object Folders Separate for each instance Class Folders Data common to all instances id2 x 2.0 y 3.0 z 5.0 id3 x 5.0 y 7.2 z -0.5???? 6

Name Resolution for Objects object. name means Go the folder for object Find attribute/method name If missing, check class folder If not in either, raise error What is in the class folder? Data common to all objects First must understand the class definition p id3 q id4 id3 id4 x 5.0 x 7.4 y 2.0 y 0.0 z 3.0 z 0.0???? 7

The Class Definition Goes inside a module, just like a function definition. class <class-name>(object): """Class specification""" <function definitions> <assignment statements> <any other statements also allowed> Example class Example(object): """The simplest possible class.""" pass 8

keyword class Beginning of a class definition Specification (similar to one for a function) to define methods to define attributes The Class Definition class <class-name>(object): """Class specification""" <function definitions> <assignment statements> more on this later <any other statements also allowed> Goes inside a module, just like a function definition. Do not forget the colon! but not often used Example class Example(object): """The simplest possible class.""" pass Python creates after reading the class definition 9

Recall: Constructors Function to create new instances Function name == class name Created for you automatically Calling the constructor: Makes a new object folder Initializes attributes Returns the id of the folder By default, takes no arguments e = Example() Will come back to this id2 e id2 Example Example 10

Instances and Attributes Assignments add object attributes <object>.<att> = <expression> Example: e.b = 42 Assignments can add class attributes <class>.<att> = <expression> Example: Example.a = 29 Objects can access class attributes Example: print e.a But assigning it creates object attribute Example: e.a = 10 Rule: check object first, then class id2 b a e id2 Example 42 Example 29 11

Instances and Attributes Assignments add object attributes <object>.<att> = <expression> Example: e.b = 42 Assignments can add class attributes <class>.<att> = <expression> Example: Example.a = 29 Objects can access class attributes Example: print e.a But assigning it creates object attribute Example: e.a = 10 Rule: check object first, then class Not how usually done id2 b a e id2 Example 42 Example 29 12

Instances and Attributes Assignments add object attributes <object>.<att> = <expression> Example: e.b = 42 Assignments can add class attributes <class>.<att> = <expression> Example: Example.a = 29 Objects can access class attributes Example: print e.a But assigning it creates object attribute Example: e.a = 10 Rule: check object first, then class id2 b a a e id2 Example 42 10 Example 29 13

Invariants Properties of an attribute that must be true Works like a precondition: If invariant satisfied, object works properly If not satisfied, object is corrupted Examples: class: all attributes must be floats RGB class: all attributes must be ints in 0..255 Purpose of the class specification 14

The Class Specification class Worker(object): """An instance is a worker in an organization. Instance has basic worker info, but no salary information. ATTRIBUTES: lname: Worker s last name. [str] ssn: Social security no. [int in 0..999999999] boss: Worker's boss. [Worker, or None if no boss] 15

The Class Specification Attribute list Attribute Name class Worker(object): """An instance is a worker in an organization. Instance has basic worker info, but no salary information. ATTRIBUTES: lname: Worker s last name. [str] ssn: Social security no. [int in 0..999999999] boss: Worker's boss. Description Short summary Invariant More detail [Worker, or None if no boss] 16

Recall: Objects can have Methods Method: function tied to object Function call: <function-name>(<arguments>) Method call: <object-variable>.<function-call> Example: p.distance(q) Both p and q act as arguments Very much like distanceto(p, q) For most Python objects Attributes are in object folder Methods are in class folder p id3 x 5.0 y 2.0 z 3.0 id3 init (x, y, z) distanceto(other) abs() q id4 x 7.4 y 0.0 z 0.0 id4 17

Method Definitions Looks like a function def But indented inside class The first parameter is always called self In a method call: Parentheses have one less argument than parameters The object in front is passed to parameter self Example: a.distance(b) self q class (object): """Instances are points in 3d space x: x coord [float] y: y coord [float] z: z coord [float] """ def distance(self,q): """Returns: dist from self to q Precondition: q a """ assert type(q) == sqrdst = ((self.x-q.x)**2 + (self.y-q.y)**2 + (self.z-q.z)**2) return math.sqrt(sqrdst) 18

Methods Calls Example: a.distance(b) a id2 b id3 id2 id3 x 1.0 x 0.0 y 2.0 y 3.0 z 3.0 z -1.0 class (object): """Instances are points in 3d space x: x coord [float] y: y coord [float] z: z coord [float] """ def distance(self,q): """Returns: dist from self to q Precondition: q a """ assert type(q) == sqrdst = ((self.x-q.x)**2 + (self.y-q.y)**2 + (self.z-q.z)**2) return math.sqrt(sqrdst) 19

Methods Calls Example: a.distance(b) a id2 b id3 id2 id3 x 1.0 x 0.0 y 2.0 y 3.0 z 3.0 z -1.0 distance 1 self id2 q id3 class (object): """Instances are points in 3d space x: x coord [float] y: y coord [float] z: z coord [float] """ def distance(self,q): """Returns: dist from self to q Precondition: q a """ assert type(q) == sqrdst = ((self.x-q.x)**2 + (self.y-q.y)**2 + (self.z-q.z)**2) return math.sqrt(sqrdst) 20

Initializing the Attributes of an Object (Folder) Creating a new Worker is a multi-step process: w = Worker() w.lname = 'White' Want to use something like w = Worker('White', 1234, None) Create a new Worker and assign attributes lname to 'White', ssn to 1234, and boss to None Need a custom constructor Instance is empty 21

Special Method: init w = Worker('White', 1234, None) def init (self, n, s, b): """Initializer: creates a Worker Has last name n, SSN s, and boss b Called by the constructor id8 Worker Precondition: n a string, s an int in range 0..999999999, and b either a Worker or None. self.lname = n self.ssn = s self.boss = b lname ssn boss 'White' 1234 None 22

Special Method: init two underscores w = Worker('White', 1234, None) don t forget self def init (self, n, s, b): """Initializer: creates a Worker Has last name n, SSN s, and boss b Precondition: n a string, s an int in range 0..999999999, and b either a Worker or None. self.lname = n self.ssn = s self.boss = b Called by the constructor id8 Worker lname 'White' ssn 1234 boss None use self to assign attributes 23

Evaluating a Constructor Expression Worker('White', 1234, None) 1. Creates a new object (folder) of the class Worker Instance is initially empty 2. Puts the folder into heap space 3. Executes the method init Passes folder name to self Passes other arguments in order Executes the (assignment) commands in initializer body 4. Returns the object (folder) name id8 lname ssn boss 'White' 1234 None Worker 24

Aside: The Value None The boss field is a problem. boss refers to a Worker object var1 id5 id5 Some workers have no boss Or maybe not assigned yet (the buck stops there) var2 id6 x 2.2 y 5.4 Solution: use value None z 6.7 None: Lack of (folder) name Will reassign the field later! Be careful with None values var3.x gives error! There is no name in var3 var3 None id6 x 3.5 y -2.0 Which Point to use? z 0.0 25

Making Arguments Optional We can assign default values to init arguments Write as assignments to parameters in definition Parameters with default values are optional Examples: p = () # (0,0,0) p = (1,2,3) # (1,2,3) p = (1,2) # (1,2,0) p = (y=3) # (0,3,0) p = (1,z=2) # (1,0,2) class (object): """Instances are points in 3d space x: x coord [float] y: y coord [float] z: z coord [float] """ def init (self,x=0,y=0,z=0): """Initializer: makes a new Point Precondition: x,y,z are numbers""" self.x = x self.y = y self.z = z 26

Making Arguments Optional We can assign default values to init arguments Write as assignments to parameters in definition Parameters with default values are optional Examples: p = () # (0,0,0) Assigns in order p = (1,2,3) # (1,2,3) p = (1,2) # (1,2,0) p = (y=3) # (0,3,0) Use parameter name when out of order p = (1,z=2) # (1,0,2) Can mix two approaches class (object): """Instances are points in 3d space x: x coord [float] y: y coord [float] z: z coord [float] """ def init (self,x=0,y=0,z=0): """Initializer: makes a new Point Precondition: x,y,z are numbers""" self.x = x self.y = y self.z = z 27

Making Arguments Optional We can assign default values to init arguments Write as assignments to parameters in definition Parameters with default values are optional Examples: p = () # (0,0,0) Assigns in order p = (1,2,3) # (1,2,3) p = (1,2) # (1,2,0) p = (y=3) # (0,3,0) Use parameter name when out of order p = (1,z=2) # (1,0,2) Can mix two approaches class (object): """Instances are points in 3d space x: x coord [float] y: y coord [float] z: z coord [float] """ def init (self,x=0,y=0,z=0): """Initializer: makes a new Point Precondition: x,y,z are numbers""" self.x = x Not limited to methods. Can do with any function. self.y = y self.z = z 28