Lecture 21. Programming with Subclasses

Similar documents
Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses

Lecture 18. Classes and Types

Review 3. Exceptions and Try-Except Blocks

Lecture 19. Operators and Abstraction

Lecture 20. Subclasses & Inheritance

CS Lecture 26: Grab Bag. Announcements

Lecture 18. Methods and Operations

Lecture 19. Using Classes Effectively

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Lecture 18: Using Classes Effectively (Chapter 16)

PREPARING FOR PRELIM 2

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Lecture 11. Asserts and Error Handling

Lecture #12: Quick: Exceptions and SQL

Exceptions & a Taste of Declarative Programming in SQL

Exceptions CS GMU

isinstance and While Loops

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

CS 11 python track: lecture 2

20. More Complicated Classes. A Class For Manipulating Fractions. A Class For Manipulating Fractions 4/19/2016. Let s Define a Class to Do This Stuff

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo)

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

CS 1110 Prelim 2 November 14th, 2013

PREPARING FOR THE FINAL EXAM

Review 2. Classes and Subclasses

Lecture 19: Subclasses & Inheritance (Chapter 18)

PREPARING FOR THE FINAL EXAM

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

61A Lecture 25. Friday, October 28

Lecture 11. Asserts and Error Handling

CSE : Python Programming

CS 1110: Introduction to Computing Using Python Loop Invariants

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

Announcements for This Lecture

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Lecture 17: Classes (Chapter 15)

Lecture 17: Classes (Chapter 15)

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

CS Prelim 2 Review Fall 2017

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Object-Oriented Python

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

Announcements for This Lecture

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

Class extension and. Exception handling. Genome 559

CS 11 python track: lecture 4

PREPARING FOR PRELIM 1

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

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

CS 11 python track: lecture 3. n Today: Useful coding idioms

CSC148 Recipe for Designing Classes

Class extension and. Exception handling. Genome 559

CS Prelim 2 Review Fall 2012

Week 2. Classes and Objects

Exception Handling and Debugging

Exceptions & error handling in Python 2 and Python 3

New York University School of Continuing and Professional Studies Management and Information Technology. Advanced Python. Homework, Session 5

LECTURE 4 Python Basics Part 3

CS Prelim 2 Review Fall 2015

Final Exam Version A

Chapter 9: Dealing with Errors

CS Prelim 2 Review Fall 2014

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

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

CS Prelim 2 Review Fall 2018

CS Lecture 19: Loop invariants

Lecture 12. Lists (& Sequences)

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

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling


CS 1110 Prelim 1 October 4th, 2012

CS 1110 Prelim 2 November 12th, 2015

Fundamentals of Programming. Week 11 - Lecture 1: OOP Part 2.

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

Announcements for this Lecture

Lecture 9. Memory and Call Stacks

CS 1110 Prelim 2 November 12th, 2015

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

SCHEME INTERPRETER GUIDE 4

Sorting and Searching

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


Python for Astronomers. Errors and Exceptions

Beyond Blocks: Python Session #1

CS1210 Lecture 28 Mar. 27, 2019

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

Exam #3, Form 3 A CSE 231 Fall 2015 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

CIS192: Python Programming

Semantic Analysis. Lecture 9. February 7, 2018

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

COMPSCI 105 S Principles of Computer Science. Classes 3

CS1110 Lab 6 (Mar 17-18, 2015)

COMP 204: Sets, Commenting & Exceptions

COMP1730/COMP6730 Programming for Scientists. Testing and Debugging.

Exceptions and File I/O

Transcription:

Lecture 21 Programming with Subclasses

Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops + Classes S/U Students are exempt Conflict with Prelim time? LAST DAY TO SUBMIT Assignments A4 is still being graded Will be done tomorrow But I looked at surveys People generally liked it Avg Time: 8.8 hrs Median: 8, STDev: 4.6 A5 is due tonight at midnight Continue working on A6 Finish Task 3 by Sunday 11/2/17 Programming with Subclasses 2

About super() super() is very limited Can only go one level BAD: super().super() p id2 Need arguments for more super(class,self) The subclass Object in the method id2 Rect Rect Poly Shape str () str () str () 11/2/17 Programming with Subclasses 3

About super() super() is very limited Can only go one level BAD: super().super() p id2 Need arguments for more super(class,self) The subclass Object in the method id2 Rect Rect Poly Shape str () str () str () p. str () 11/2/17 Programming with Subclasses 4

About super() super() is very limited Can only go one level BAD: super().super() p id2 Need arguments for more super(class,self) The subclass Object in the method id2 Rect Rect super(rect,self). str () Poly Shape str () str () str () p. str () super(). str () 11/2/17 Programming with Subclasses 5

About super() super() is very limited Can only go one level BAD: super().super() p id2 Need arguments for more super(class,self) The subclass Object in the method id2 Rect Rect super(rect,self). str () Poly Shape str () str () str () p. str () super(). str () super(poly,self). str () 11/2/17 Programming with Subclasses 6

A Problem with Subclasses class Fraction(object): """Instances are normal fractions n/d Instance attributes: numerator: top [int] denominator: bottom [int > 0] """ class BinaryFraction(Fraction): """Instances are fractions k/2 n Instance attributes are same, BUT: numerator: top [int] denominator: bottom [= 2 n, n 0] """ def init (self,k,n): """Make fraction k/2 n """ assert type(n) == int and n >= 0 super(). init (k,2 ** n) >>> p = Fraction(1,2) >>> q = BinaryFraction(1,2) # 1/4 >>> r = p*q Python converts to >>> r = p. mul (q) # ERROR mul has precondition type(q) == Fraction 11/2/17 Programming with Subclasses 7

The isinstance Function isinstance(<obj>,<class>) True if <obj> s class is same as or a subclass of <class> False otherwise Example: isinstance(e,executive) is True isinstance(e,employee) is True isinstance(e,object) is True isinstance(e,str) is False Generally preferable to type Works with base types too! e id4 id4 Executive _name 'Fred' _start 2012 _salary 0.0 _bonus 0.0 object Employee Executive 11/2/17 Programming with Subclasses 8

isinstance and Subclasses >>> e = Employee('Bob',2011) >>> isinstance(e,executive)??? A: True B: False C: Error D: I don t know e id5 id5 Employee _name 'Bob' _start 2012 _salary 50k object Employee Executive 11/2/17 Programming with Subclasses 9

isinstance and Subclasses >>> e = Employee('Bob',2011) >>> isinstance(e,executive)??? A: True B: False Correct C: Error D: I don t know object Employee Executive means extends or is an instance of 11/2/17 Programming with Subclasses 10

Fixing Multiplication class Fraction(object): """Instance attributes: numerator [int]: top denominator [int > 0]: bottom""" def mul (self,q): """Returns: Product of self, q Makes a new Fraction; does not modify contents of self or q Precondition: q a Fraction""" assert isinstance(q, Fraction) top = self.numerator*q.numerator bot = self.denominator*q.denominator return Fraction(top,bot) >>> p = Fraction(1,2) >>> q = BinaryFraction(1,2) # 1/4 >>> r = p*q Python converts to >>> r = p. mul (q) # OKAY Can multiply so long as it has numerator, denominator 11/2/17 Programming with Subclasses 11

Error Types in Python def foo(): assert 1 == 2, 'My error' def foo(): x = 5 / 0 >>> foo() AssertionError: My error Class Names >>> foo() ZeroDivisionError: integer division or modulo by zero 11/2/17 Programming with Subclasses 12

Error Types in Python def foo(): assert 1 == 2, 'My error' >>> foo() AssertionError: My error Class Names def foo(): Information about an error is x stored = 5 / inside 0 an object. The error type is the class of the error object. >>> foo() ZeroDivisionError: integer division or modulo by zero 11/2/17 Programming with Subclasses 13

Error Types in Python All errors are instances of class BaseException This allows us to organize them in a hierarchy BaseException init (msg) str () Exception(BE) BaseException Exception id4 AssertionError 'My error' AssError(SE) AssertionError means extends or is an instance of 11/2/17 Programming with Subclasses 14

Error Types in Python All errors are instances of class BaseException This allows us to organize them in a hierarchy BaseException init (msg) str () Exception(BE) BaseException All of these are actually Exception empty! Why? id4 AssertionError 'My error' AssError(SE) AssertionError means extends or is an instance of 11/2/17 Programming with Subclasses 15

Python Error Type Hierarchy SystemExit BaseException Exception Argument has wrong type (e.g. float([1])) Argument has wrong value (e.g. float('a')) AssertionError AttributeError ArithmeticError IOError TypeError ValueError ZeroDivisionError OverflowError http://docs.python.org/ library/exceptions.html Why so many error types? 11/2/17 Programming with Subclasses 16

Recall: Recovering from Errors try-except blocks allow us to recover from errors Do the code that is in the try-block Once an error occurs, jump to the catch Example: try: val = input() # get number from user x = float(val) # convert string to float print('the next number is '+str(x+1)) except: print('hey! That is not a number!') might have an error executes if have an error 11/2/17 Programming with Subclasses 17

Handling Errors by Type try-except blocks can be restricted to specific errors Doe except if error is an instance of that type If error not an instance, do not recover Example: try: val = input() x = float(val) # get number from user # convert string to float print('the next number is '+str(x+1)) except ValueError: print('hey! That is not a number!') May have IOError May have ValueError Only recovers ValueError. Other errors ignored. 11/2/17 Programming with Subclasses 18

Handling Errors by Type try-except blocks can be restricted to specific errors Doe except if error is an instance of that type If error not an instance, do not recover Example: try: val = input() x = float(val) # get number from user # convert string to float print('the next number is '+str(x+1)) except IOError: print('check your keyboard!') May have IOError May have ValueError Only recovers IOError. Other errors ignored. 11/2/17 Programming with Subclasses 19

Creating Errors in Python Create errors with raise Usage: raise <exp> exp evaluates to an object An instance of Exception Tailor your error types ValueError: Bad value TypeError: Bad type Still prefer asserts for preconditions, however Compact and easy to read def foo(x): assert x < 2, 'My error' def foo(x): if x >= 2: m = 'My error' err = AssertionError(m) raise err Identical 11/2/17 Programming with Subclasses 20

Creating Errors in Python Create errors with raise Usage: raise <exp> exp evaluates to an object An instance of Exception Tailor your error types ValueError: Bad value TypeError: Bad type Still prefer asserts for preconditions, however Compact and easy to read def foo(x): assert x < 2, 'My error' def foo(x): if x >= 2: m = 'My error' err = TypeError(m) raise err Identical 11/2/17 Programming with Subclasses 21

Raising and Try-Except def foo(): x = 0 try: raise Exception() x = 2 except Exception: x = 3 return x The value of foo()? A: 0 B: 2 C: 3 D: No value. It stops! E: I don t know 11/2/17 Programming with Subclasses 22

Raising and Try-Except def foo(): x = 0 try: raise Exception() x = 2 except Exception: x = 3 return x The value of foo()? A: 0 B: 2 C: 3 Correct D: No value. It stops! E: I don t know 11/2/17 Programming with Subclasses 23

Raising and Try-Except def foo(): x = 0 try: raise Exception() x = 2 except BaseException: x = 3 return x The value of foo()? A: 0 B: 2 C: 3 D: No value. It stops! E: I don t know 11/2/17 Programming with Subclasses 24

Raising and Try-Except def foo(): x = 0 try: raise Exception() x = 2 except BaseException: x = 3 return x The value of foo()? A: 0 B: 2 C: 3 Correct D: No value. It stops! E: I don t know 11/2/17 Programming with Subclasses 25

Raising and Try-Except def foo(): x = 0 try: raise Exception() x = 2 except AssertionError: x = 3 return x The value of foo()? A: 0 B: 2 C: 3 D: No value. It stops! E: I don t know 11/2/17 Programming with Subclasses 26

Raising and Try-Except def foo(): x = 0 try: raise Exception() x = 2 except AssertionError: x = 3 return x The value of foo()? A: 0 B: 2 C: 3 D: No value. Correct It stops! E: I don t know Python uses isinstance to match Error types 11/2/17 Programming with Subclasses 27

Creating Your Own Exceptions class CustomError(Exception): """An instance is a custom exception""" pass This is all you need No extra fields No extra methods No constructors Inherit everything Only issues is choice of parent error class. Use Exception if you are unsure what. 11/2/17 Programming with Subclasses 28

Handling Errors by Type try-except can put the error in a variable Example: try: val = input() x = float(val) # get number from user # convert string to float print('the next number is '+str(x+1)) except ValueError as e: print(e.args[0]) print('hey! That is not a number!') Some Error subclasses have more attributes 11/2/17 Programming with Subclasses 29

Accessing Attributes with Strings hasattr(<obj>,<name>) Checks if attribute exists getattr(<obj>,<name>) Reads contents of attribute delattr(<obj>,<name>) Deletes the given attribute setattr(<obj>,<name>,<val>) Sets the attribute value <obj>. dict List all attributes of object 11/2/17 Programming with Subclasses 30 id1 x y z Point3 2.0 3.0 5.0 id2 'x' 'y' 'z' Treat object like dictionary 2.0 3.0 5.0 dict

Typing Philosophy in Python Duck Typing: Type object is determined by its methods and properties Not the same as type() value Preferred by Python experts Implement with hasattr() hasattr(<object>,<string>) Returns true if object has an attribute/method of that name This has many problems The name tells you nothing about its specification class Fraction(object): """Instance attributes: numerator [int]: top denominator [int > 0]: bottom""" def eq (self,q): """Returns: True if self, q equal, False if not, or q not a Fraction""" if type(q)!= Fraction: return False left = self.numerator*q.denominator rght = self.denominator*q.numerator return left == rght 11/2/17 Programming with Subclasses 31

Typing Philosophy in Python Duck Typing: Type object is determined by its methods and properties Not the same as type() value Preferred by Python experts Implement with hasattr() hasattr(<object>,<string>) Returns true if object has an attribute/method of that name This has many problems The name tells you nothing about its specification class Fraction(object): """Instance attributes: numerator [int]: top denominator [int > 0]: bottom""" def eq (self,q): """Returns: True if self, q equal, False if not, or q not a Fraction""" if (not (hasattr(q,'numerator') and hasattr(q,'denomenator')): return False left = self.numerator*q.denominator rght = self.denominator*q.numerator return left == rght 11/2/17 Programming with Subclasses 32

Duck Typing: Typing Philosophy in Python Type object is determined by its methods and properties Not the same as type() value Preferred Compares by Python anything expertswith Implement numerator with hasattr() & denominator hasattr(<object>,<string>) Returns true if object has an attribute/method of that name This has many problems The name tells you nothing about its specification class Fraction(object): """Instance attributes: numerator [int]: top denominator [int > 0]: bottom""" def eq (self,q): """Returns: True if self, q equal, False if not, or q not a Fraction""" if (not (hasattr(q,'numerator') and hasattr(q,'denomenator')): return False left = self.numerator*q.denominator rght = self.denominator*q.numerator return left == rght 11/2/17 Programming with Subclasses 33

Duck Typing: Typing Philosophy in Python Type object is determined by its methods Howand to properly propertiesimplement/use typing Not the same is a as major type() debate value in language design Preferred by What Pythonwe experts really care def about eq (self,q): is Implement with specifications hasattr() (and invariants) hasattr(<object>,<string>) Types are a shorthand for this Returns true Different object typing has an styles trade ease-of-use attribute/method with overall of that program name robustness/safety return False This has many problems The name tells you nothing about its specification class Fraction(object): """Instance attributes: numerator [int] : top denominator [int > 0]: bottom""" """Returns: True if self, q equal, False if not, or q not a Fraction""" if (not (hasattr(q,'numerator') and hasattr(q,'denomenator')): left = self.numerator*q.denominator rght = self.denominator*q.numerator return left == rght 11/2/17 Programming with Subclasses 34

Typing Philosophy in Python Duck Typing: Type object is determined by its methods and properties Not the same as type() value Preferred by Python experts Implement with hasattr() hasattr(<object>,<string>) Returns true if object has an attribute/method of that name This has many problems The name tells you nothing about its specification class Employee(object): """An Employee with a salary" " def eq (self,other): if (not (hasattr(other,'name') and hasattr(other,'start') and hasattr(other,'salary')) return False return (self.name == other.name and self.start == other.start and self.salary == other.salary) 11/2/17 Programming with Subclasses 35