programming with subclasses announcements for this lecture
play

Programming with Subclasses Announcements for This Lecture - PowerPoint PPT Presentation

Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 Thursday, 5:15 or 7:30 A4 is now graded K Z at 5:15pm Mean : 90.4 Median : 93 A J at 7:30 pm Std Dev : 10.6 See website


  1. Lecture 21 Programming with Subclasses

  2. Announcements for This Lecture Assignments Prelim 2 • Thursday, 5:15 or 7:30 • A4 is now graded § K – Z at 5:15pm § Mean : 90.4 Median : 93 § A – J at 7:30 pm § Std Dev : 10.6 § See website for room § Mean : 9 hrs Median : 8 hrs § Conflicts received e-mail § Std Dev : 4.1 hrs • A5 is also graded • ANOTHER review Wed. § Run by the URMC § Mean : 46.4 Median : 49 § Open up to everyone § A : 47 (74%), B : 40 (19%) § Solutions posted in CMS 11/6/18 Programming with Subclasses 2

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

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

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

  6. isinstance and Subclasses >>> e = Employee('Bob',2011) object >>> isinstance(e,Executive) ??? Employee A: True B: False Correct Executive C: Error D: I don’t know → means “extends” or “is an instance of” 11/6/18 Programming with Subclasses 6

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

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

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

  10. Error Types in Python • All errors are instances of class BaseException • This allows us to organize them in a hierarchy BaseException BaseException __init__(msg) id4 __str__() AssertionError … Exception 'My error' Exception(BE) → means “extends” AssertionError or “is an instance of” AssError(SE) 11/6/18 Programming with Subclasses 10

  11. Error Types in Python • All errors are instances of class BaseException • This allows us to organize them in a hierarchy BaseException BaseException __init__(msg) id4 __str__() All of these are AssertionError … Exception actually empty! 'My error' Why? Exception(BE) → means “extends” AssertionError or “is an instance of” AssError(SE) 11/6/18 Programming with Subclasses 11

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

  13. 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: might have an error val = input() # get number from user x = float(val) # convert string to float print('The next number is '+str(x+1)) except: executes if have an error print('Hey! That is not a number!') 11/6/18 Programming with Subclasses 13

  14. 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: May have IOError val = input() # get number from user x = float(val) # convert string to float print('The next number is '+str(x+1)) May have ValueError except ValueError: Only recovers ValueError. Other errors ignored. print('Hey! That is not a number!') 11/6/18 Programming with Subclasses 14

  15. 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: May have IOError val = input() # get number from user x = float(val) # convert string to float print('The next number is '+str(x+1)) May have ValueError except IOError: Only recovers IOError. Other errors ignored. print('Check your keyboard!') 11/6/18 Programming with Subclasses 15

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

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

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

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

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

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

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

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

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

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend