Programming with Subclasses Announcements for Today Reading - - PowerPoint PPT Presentation

programming with subclasses announcements for today
SMART_READER_LITE
LIVE PREVIEW

Programming with Subclasses Announcements for Today Reading - - PowerPoint PPT Presentation

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


slide-1
SLIDE 1

Programming with Subclasses

Lecture 21

slide-2
SLIDE 2

Announcements for Today Reading

  • Today: See reading online
  • Tuesday: Chapter 7

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

  • Prelim, Nov 9th 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

slide-3
SLIDE 3

About super()

  • super() is very limited

§ Can only go one level § BAD: super().super()

  • Need arguments for more

§ super(class,self)

11/2/17 Programming with Subclasses 3

The subclass Object in the method

Rect

__str__()

Poly

__str__()

Shape

__str__() id2

Rect p id2

slide-4
SLIDE 4

About super()

  • super() is very limited

§ Can only go one level § BAD: super().super()

  • Need arguments for more

§ super(class,self)

11/2/17 Programming with Subclasses 4

The subclass Object in the method

Rect

__str__()

Poly

__str__()

Shape

__str__() id2

Rect p id2 p.__str__()

slide-5
SLIDE 5

About super()

  • super() is very limited

§ Can only go one level § BAD: super().super()

  • Need arguments for more

§ super(class,self)

11/2/17 Programming with Subclasses 5

The subclass Object in the method

Rect

__str__()

Poly

__str__()

Shape

__str__() id2

Rect p id2 p.__str__() super().__str__() super(Rect,self).__str__()

slide-6
SLIDE 6

About super()

  • super() is very limited

§ Can only go one level § BAD: super().super()

  • Need arguments for more

§ super(class,self)

11/2/17 Programming with Subclasses 6

The subclass Object in the method

Rect

__str__()

Poly

__str__()

Shape

__str__() id2

Rect p id2 p.__str__() super().__str__() super(Rect,self).__str__() super(Poly,self).__str__()

slide-7
SLIDE 7

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/2n Instance attributes are same, BUT: numerator: top [int] denominator: bottom [= 2n, n ≥ 0] """ def __init__(self,k,n): """Make fraction k/2n """ 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 >>> r = p.__mul__(q) # ERROR

Python converts to

__mul__ has precondition type(q) == Fraction

11/2/17 Programming with Subclasses 7

A Problem with Subclasses

slide-8
SLIDE 8

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!

11/2/17 Programming with Subclasses 8

e id4

id4

Executive

_salary 0.0 _start 2012 _name 'Fred' _bonus 0.0

  • bject

Employee Executive

slide-9
SLIDE 9

isinstance and Subclasses

>>> e = Employee('Bob',2011) >>> isinstance(e,Executive) ???

11/2/17 Programming with Subclasses 9

A: True B: False C: Error D: I don’t know

e id5

id5

Employee

_salary 50k _start 2012 _name 'Bob'

  • bject

Employee Executive

slide-10
SLIDE 10

isinstance and Subclasses

>>> e = Employee('Bob',2011) >>> isinstance(e,Executive) ???

11/2/17 Programming with Subclasses 10

A: True B: False C: Error D: I don’t know

  • bject

Executive Employee

→ means “extends”

  • r “is an instance of”

Correct

slide-11
SLIDE 11

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 >>> r = p.__mul__(q) # OKAY

Python converts to

Can multiply so long as it has numerator, denominator

11/2/17 Programming with Subclasses 11

slide-12
SLIDE 12

Error Types in Python

def foo(): assert 1 == 2, 'My error' … >>> foo() AssertionError: My error def foo(): x = 5 / 0 … >>> foo() ZeroDivisionError: integer division or modulo by zero

11/2/17 Programming with Subclasses 12

Class Names

slide-13
SLIDE 13

Error Types in Python

def foo(): assert 1 == 2, 'My error' … >>> foo() AssertionError: My error def foo(): x = 5 / 0 … >>> foo() ZeroDivisionError: integer division or modulo by zero

11/2/17 Programming with Subclasses 13

Class Names Information about an error is stored inside an object. The error type is the class

  • f the error object.
slide-14
SLIDE 14

Error Types in Python

  • All errors are instances of class BaseException
  • This allows us to organize them in a hierarchy

11/2/17 Programming with Subclasses 14

BaseException AssertionError Exception

id4

AssertionError 'My error'

→ means “extends”

  • r “is an instance of”

__init__(msg) __str__() …

BaseException Exception(BE) AssError(SE)

slide-15
SLIDE 15

Error Types in Python

  • All errors are instances of class BaseException
  • This allows us to organize them in a hierarchy

11/2/17 Programming with Subclasses 15

id4

AssertionError 'My error'

→ means “extends”

  • r “is an instance of”

BaseException AssertionError Exception

__init__(msg) __str__() …

BaseException Exception(BE) AssError(SE)

All of these are actually empty! Why?

slide-16
SLIDE 16

Python Error Type Hierarchy

11/2/17 Programming with Subclasses 16

BaseException Exception SystemExit

AssertionError ArithmeticError AttributeError ValueError TypeError IOError … ZeroDivisionError OverflowError

… Argument has wrong type (e.g. float([1])) Argument has wrong value (e.g. float('a'))

Why so many error types?

http://docs.python.org/ library/exceptions.html

slide-17
SLIDE 17

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 17 Programming with Subclasses

slide-18
SLIDE 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() # get number from user x = float(val) # convert string to float print('The next number is '+str(x+1)) except ValueError: print('Hey! That is not a number!')

Only recovers ValueError. Other errors ignored.

11/2/17 18 Programming with Subclasses

May have ValueError May have IOError

slide-19
SLIDE 19

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() # get number from user x = float(val) # convert string to float print('The next number is '+str(x+1)) except IOError: print('Check your keyboard!')

Only recovers IOError. Other errors ignored.

11/2/17 19 Programming with Subclasses

May have ValueError May have IOError

slide-20
SLIDE 20

Creating Errors in Python

def foo(x): assert x < 2, 'My error' … def foo(x): if x >= 2: m = 'My error' err = AssertionError(m) raise err

11/2/17 Programming with Subclasses 20

  • 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 Identical

slide-21
SLIDE 21

Creating Errors in Python

def foo(x): assert x < 2, 'My error' … def foo(x): if x >= 2: m = 'My error' err = TypeError(m) raise err

11/2/17 Programming with Subclasses 21

  • 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 Identical

slide-22
SLIDE 22

Raising and Try-Except

def foo(): x = 0 try: raise Exception() x = 2 except Exception: x = 3 return x

  • The value of foo()?

11/2/17 Programming with Subclasses 22

A: 0 B: 2 C: 3 D: No value. It stops! E: I don’t know

slide-23
SLIDE 23

Raising and Try-Except

def foo(): x = 0 try: raise Exception() x = 2 except Exception: x = 3 return x

  • The value of foo()?

11/2/17 Programming with Subclasses 23

A: 0 B: 2 C: 3 D: No value. It stops! E: I don’t know Correct

slide-24
SLIDE 24

Raising and Try-Except

def foo(): x = 0 try: raise Exception() x = 2 except BaseException: x = 3 return x

  • The value of foo()?

11/2/17 Programming with Subclasses 24

A: 0 B: 2 C: 3 D: No value. It stops! E: I don’t know

slide-25
SLIDE 25

Raising and Try-Except

def foo(): x = 0 try: raise Exception() x = 2 except BaseException: x = 3 return x

  • The value of foo()?

11/2/17 Programming with Subclasses 25

A: 0 B: 2 C: 3 D: No value. It stops! E: I don’t know Correct

slide-26
SLIDE 26

Raising and Try-Except

def foo(): x = 0 try: raise Exception() x = 2 except AssertionError: x = 3 return x

  • The value of foo()?

11/2/17 Programming with Subclasses 26

A: 0 B: 2 C: 3 D: No value. It stops! E: I don’t know

slide-27
SLIDE 27

Raising and Try-Except

def foo(): x = 0 try: raise Exception() x = 2 except AssertionError: x = 3 return x

  • The value of foo()?

11/2/17 Programming with Subclasses 27

A: 0 B: 2 C: 3 D: No value. It stops! E: I don’t know Correct

Python uses isinstance to match Error types

slide-28
SLIDE 28

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

11/2/17 28 Programming with Subclasses

Only issues is choice

  • f parent error class.

Use Exception if you are unsure what.

slide-29
SLIDE 29

Handling Errors by Type

  • try-except can put the error in a variable
  • Example:

try: val = input() # get number from user x = float(val) # 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!')

11/2/17 29 Programming with Subclasses

Some Error subclasses have more attributes

slide-30
SLIDE 30

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 2.0 3.0 5.0

Point3

x y z id2 2.0 3.0 5.0

dict

'x' 'y' 'z'

Treat object like dictionary

slide-31
SLIDE 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

11/2/17 Programming with Subclasses 31

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

slide-32
SLIDE 32

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

11/2/17 Programming with Subclasses 32

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

slide-33
SLIDE 33

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

11/2/17 Programming with Subclasses 33

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

Compares anything with numerator & denominator

slide-34
SLIDE 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

11/2/17 Programming with Subclasses 34

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

How to properly implement/use typing is a major debate in language design

  • What we really care about is

specifications (and invariants)

  • Types are a “shorthand” for this

Different typing styles trade ease-of-use with overall program robustness/safety

slide-35
SLIDE 35

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