Lecture 21 Programming with Subclasses
Announcements for Today Reading Assignments • Today: See reading online • A4 is still being graded § Will be done tomorrow • Tuesday: Chapter 7 • But I looked at surveys • Prelim, Nov 9 th 7:30-9:00 § People generally liked it § Material up to Today § Review has been posted § Avg Time : 8.8 hrs § Recursion + Loops + Classes § Median : 8, STDev : 4.6 • S/U Students are exempt • A5 is due tonight at midnight • Conflict with Prelim time? • Continue working on A6 § LAST DAY TO SUBMIT § Finish Task 3 by Sunday 11/2/17 Programming with Subclasses 2
About super() • super() is very limited • Need arguments for more § Can only go one level § super(class,self) § BAD : super().super() Object in The subclass the method p id2 id2 Rect Rect Poly Shape __str__() __str__() __str__() 11/2/17 Programming with Subclasses 3
About super() • super() is very limited • Need arguments for more § Can only go one level § super(class,self) § BAD : super().super() Object in The subclass the method p id2 id2 Rect Rect Poly Shape __str__() __str__() __str__() p.__str__() 11/2/17 Programming with Subclasses 4
About super() • super() is very limited • Need arguments for more § Can only go one level § super(class,self) § BAD : super().super() Object in The subclass the method p id2 id2 super(Rect,self).__str__() Rect Rect Poly Shape __str__() __str__() __str__() p.__str__() super().__str__() 11/2/17 Programming with Subclasses 5
About super() • super() is very limited • Need arguments for more § Can only go one level § super(class,self) § BAD : super().super() Object in The subclass the method p id2 id2 super(Rect,self).__str__() Rect Rect 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): >>> 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/2/17 Programming with Subclasses 7
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 2012 _start § 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/2/17 Programming with Subclasses 8
isinstance and Subclasses >>> e = Employee('Bob',2011) e object id5 >>> isinstance(e,Executive) ??? id5 Employee Employee A: True _name 'Bob' B: False 2012 C: Error _start D: I don’t know Executive 50k _salary 11/2/17 Programming with Subclasses 9
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/2/17 Programming with Subclasses 10
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/2/17 Programming with Subclasses 11
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/2/17 Programming with Subclasses 12
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/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 BaseException __init__(msg) id4 __str__() AssertionError … Exception 'My error' Exception(BE) → means “extends” AssertionError or “is an instance of” AssError(SE) 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 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/2/17 Programming with Subclasses 15
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/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: 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/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: 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/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: 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/2/17 Programming with Subclasses 19
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/2/17 Programming with Subclasses 20
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/2/17 Programming with Subclasses 21
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/2/17 Programming with Subclasses 22
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/2/17 Programming with Subclasses 23
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/2/17 Programming with Subclasses 24
Recommend
More recommend