overview - dipartimento di...

299
Recap of FP Classes Instances Inheritance Exceptions Overview

Upload: others

Post on 04-Jun-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Recap of FPClassesInstancesInheritanceExceptions

Overview

Page 2: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

< , , , >

[len(s) for s in languages]["python", "perl", "java", "c++"]

46 4 3

map(len, languages)

Page 3: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

< , , >

[num for num in fibs if is_even(num)]

[1, 1, 2, 3, 5, 8, 13, 21, 34]

82 34

filter(is_even, fibs)

Page 4: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Function Definitions vs. Lambdas

Page 5: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def greet(): print("Hi!")

Function Definitions vs. Lambdasdef binds a function object

to a namefunction

bytecode

greet

greet

Page 6: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def greet(): print("Hi!")

lambda val: val ** 2lambda x, y: x * ylambda pair: pair[0] * pair[1]

Function Definitions vs. Lambdasdef binds a function object

to a name

lambda only creates a function object

function

bytecode

<lambda>

function

bytecode

greet

greet

Page 7: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def greet(): print("Hi!")

lambda val: val ** 2lambda x, y: x * ylambda pair: pair[0] * pair[1]

(lambda x: x > 3)(4) # => True

Function Definitions vs. Lambdasdef binds a function object

to a name

lambda only creates a function object

function

bytecode

<lambda>

function

bytecode

greet

greet

Page 8: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def debug(function): def wrapper(*args, **kwargs): print("Arguments:", args, kwargs) return function(*args, **kwargs) return wrapper

@debug def foo(a, b, c=1): return (a + b) * c

Our First Decorator

Page 9: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Object-Oriented Python

Page 10: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Recall: Programming Paradigms

Page 11: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Recall: Programming ParadigmsProcedural

Sequence of instructions that inform the computer what to do with the program's input

ExamplesC

PascalUnix (sh)

Page 12: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Recall: Programming ParadigmsProcedural

Sequence of instructions that inform the computer what to do with the program's input

ExamplesC

PascalUnix (sh)

Declarative Specification describes the problem to be solved, and

language implementation figures out the details

ExamplesSQL

Prolog

Page 13: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Recall: Programming ParadigmsProcedural

Sequence of instructions that inform the computer what to do with the program's input

ExamplesC

PascalUnix (sh)

Object-Oriented Deal with collections of objects which maintain internal

state and support methods that query or modify this internal state in some way.

ExamplesJava

Smalltalk

Declarative Specification describes the problem to be solved, and

language implementation figures out the details

ExamplesSQL

Prolog

Page 14: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Recall: Programming ParadigmsProcedural

Sequence of instructions that inform the computer what to do with the program's input

ExamplesC

PascalUnix (sh)

Object-Oriented Deal with collections of objects which maintain internal

state and support methods that query or modify this internal state in some way.

ExamplesJava

Smalltalk

FunctionalDecomposes into a set of functions, each of which solely takes inputs and produces outputs with no internal state.

ExamplesHaskellOCaml

ML

Declarative Specification describes the problem to be solved, and

language implementation figures out the details

ExamplesSQL

Prolog

Page 15: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Recall: Programming ParadigmsProcedural

Sequence of instructions that inform the computer what to do with the program's input

ExamplesC

PascalUnix (sh)

Object-Oriented Deal with collections of objects which maintain internal

state and support methods that query or modify this internal state in some way.

ExamplesJava

Smalltalk

FunctionalDecomposes into a set of functions, each of which solely takes inputs and produces outputs with no internal state.

ExamplesHaskellOCaml

ML

Declarative Specification describes the problem to be solved, and

language implementation figures out the details

ExamplesSQL

Prolog

Multi-Paradigm Supports several different

paradigms, to be combined freely

ExamplesScalaC++

Python

Page 16: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Objects, Names, Attributes

Page 17: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Some Definitions

name

Page 18: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

An object has identity

Some Definitions

name

Page 19: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

An object has identityA name is a reference to an object

Some Definitions

name

Page 20: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

An object has identityA name is a reference to an objectA namespace is an associative mapping from names to objects

Some Definitions

name

Page 21: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

An object has identityA name is a reference to an objectA namespace is an associative mapping from names to objectsAn attribute is any name following a dot ('.')

Some Definitions

type

object

identity

name

Page 22: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Classes

Page 23: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class Definition Syntax

Page 24: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class ClassName: <statement> <statement> ...

Page 25: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class ClassName: <statement> <statement> ...

The class keyword introduces a new class defintion

Page 26: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class ClassName: <statement> <statement> ...

The class keyword introduces a new class defintion

Must be executed to have effect (like def)

Page 27: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class Definitions

Page 28: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Statements are usually assignments or function definitions

Class Definitions

Page 29: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Statements are usually assignments or function definitionsEntering a class definition creates a new "namespace" - ish

Class Definitions

Page 30: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Statements are usually assignments or function definitionsEntering a class definition creates a new "namespace" - ishExiting a class definition creates a class object

Class Definitions

Page 31: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Statements are usually assignments or function definitionsEntering a class definition creates a new "namespace" - ishExiting a class definition creates a class object

Defining a class == creating a class object (like int, str)

Class Definitions

Page 32: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Statements are usually assignments or function definitionsEntering a class definition creates a new "namespace" - ishExiting a class definition creates a class object

Defining a class == creating a class object (like int, str)

Defining a class != instantiating a class

Class Definitions

Page 33: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Wait, What?

Page 34: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Defining a class creates a class object Supports attribute reference and instantiation

Instantiating a class object creates an instance object Only supports attribute reference

Class Objects vs. Instance Objects

Page 35: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class Objects

Support (1) attribute references and (2) instantation

Page 36: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class Attribute References

Page 37: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class Attribute References

Page 38: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class MyClass: """A simple example class""" num = 12345 def greet(self): return "Hello world!"

Class Attribute References

Page 39: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class MyClass: """A simple example class""" num = 12345 def greet(self): return "Hello world!"

# Attribute ReferencesMyClass.num # => 12345 (int object)MyClass.greet # => <function f> (function object)

Class Attribute References

Page 40: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class MyClass: """A simple example class""" num = 12345 def greet(self): return "Hello world!"

# Attribute ReferencesMyClass.num # => 12345 (int object)MyClass.greet # => <function f> (function object)

Class Attribute References

Warning! Class attributes can be written to by the client

Page 41: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class Instantiation

Page 42: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass(args)

Class Instantiation

Page 43: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass(args)

Class Instantiation

No new

Page 44: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass(args)

Class Instantiation

Classes are instantiated using parentheses and an argument listNo new

Page 45: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass(args)

Class Instantiation

Classes are instantiated using parentheses and an argument listNo new

Instantiating a class constructs an instance object of that class object. In this case, x is an instance object of the MyClass class object

Page 46: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Custom Constructor using __init__

Page 47: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Complex: def __init__(self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart

Custom Constructor using __init__

Page 48: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Complex: def __init__(self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart

Custom Constructor using __init__

Class instantiation calls the special method __init__ if it exists

Page 49: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Complex: def __init__(self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart

# Make an instance object `c`!c = Complex(3.0, -4.5)

Custom Constructor using __init__

Class instantiation calls the special method __init__ if it exists

Page 50: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Complex: def __init__(self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart

# Make an instance object `c`!c = Complex(3.0, -4.5)c.real, c.imag # => (3.0, -4.5)

Custom Constructor using __init__

Class instantiation calls the special method __init__ if it exists

Page 51: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Complex: def __init__(self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart

# Make an instance object `c`!c = Complex(3.0, -4.5)c.real, c.imag # => (3.0, -4.5)

Custom Constructor using __init__

Class instantiation calls the special method __init__ if it exists

You can't overload __init__! Use keyword arguments or factory methods

Page 52: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Instance Objects

Only support attribute references

Page 53: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Data Attributes = "instance variables" = "data members"

Attribute references first search the instance's __dict__ attribute, then the class object's

Page 54: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

c = Complex(3.0, -4.5)

Data Attributes = "instance variables" = "data members"

Attribute references first search the instance's __dict__ attribute, then the class object's

Page 55: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

c = Complex(3.0, -4.5)c.real, c.imag # => (3.0, -4.5)

Data Attributes = "instance variables" = "data members"

Attribute references first search the instance's __dict__ attribute, then the class object's

Page 56: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

c = Complex(3.0, -4.5)c.real, c.imag # => (3.0, -4.5)

Data Attributes = "instance variables" = "data members"

Attribute references first search the instance's __dict__ attribute, then the class object's

Page 57: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

c = Complex(3.0, -4.5)c.real, c.imag # => (3.0, -4.5)

c.real = -9.2

Data Attributes = "instance variables" = "data members"

Attribute references first search the instance's __dict__ attribute, then the class object's

Page 58: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

c = Complex(3.0, -4.5)c.real, c.imag # => (3.0, -4.5)

c.real = -9.2c.imag = 4.1

Data Attributes = "instance variables" = "data members"

Attribute references first search the instance's __dict__ attribute, then the class object's

Page 59: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Setting Data Attributes

Page 60: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

# You can set attributes on instance (and class) objects# on the fly (we used this in the constructor!)

Setting Data Attributes

Page 61: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

# You can set attributes on instance (and class) objects# on the fly (we used this in the constructor!)c.counter = 1

Setting Data Attributes

Page 62: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

# You can set attributes on instance (and class) objects# on the fly (we used this in the constructor!)c.counter = 1while c.counter < 10: c.counter = x.counter * 2 print(c.counter)del c.counter # Leaves no trace

Setting Data Attributes

Page 63: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

# You can set attributes on instance (and class) objects# on the fly (we used this in the constructor!)c.counter = 1while c.counter < 10: c.counter = x.counter * 2 print(c.counter)del c.counter # Leaves no trace

# prints 1, 2, 4, 8

Setting Data Attributes

Page 64: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

# You can set attributes on instance (and class) objects# on the fly (we used this in the constructor!)c.counter = 1while c.counter < 10: c.counter = x.counter * 2 print(c.counter)del c.counter # Leaves no trace

# prints 1, 2, 4, 8

Setting Data Attributes

Setting attributes actually inserts into the instance object's __dict__ attribute

Page 65: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class MyClass: """A simple example class""" num = 12345 def greet(self): return "Hello world!"

A Sample Class

Page 66: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Calling Methods

Page 67: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()

Calling Methods

Page 68: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()x.greet() # 'Hello world!'

Calling Methods

Page 69: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()x.greet() # 'Hello world!'# Weird... doesn't `greet` accept an argument?

Calling Methods

Page 70: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()x.greet() # 'Hello world!'# Weird... doesn't `greet` accept an argument?

Calling Methods

Page 71: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()x.greet() # 'Hello world!'# Weird... doesn't `greet` accept an argument?

print(type(x.greet)) # method

Calling Methods

Page 72: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()x.greet() # 'Hello world!'# Weird... doesn't `greet` accept an argument?

print(type(x.greet)) # methodprint(type(MyClass.greet)) # function

Calling Methods

Page 73: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()x.greet() # 'Hello world!'# Weird... doesn't `greet` accept an argument?

print(type(x.greet)) # methodprint(type(MyClass.greet)) # function

Calling Methods

Page 74: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MyClass()x.greet() # 'Hello world!'# Weird... doesn't `greet` accept an argument?

print(type(x.greet)) # methodprint(type(MyClass.greet)) # function

print(x.num is MyClass.num) # True

Calling Methods

Page 75: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Methods vs. Functions

Page 76: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method is a function bound to an objectmethod ≈ (object, function)

Methods calls invoke special semanticsobject.method(arguments) = function(object, arguments)

Methods vs. Functions

Page 77: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Pizza

Page 78: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Pizza:

Pizza

Page 79: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Pizza: def __init__(self, radius, toppings, slices=8): self.radius = radius self.toppings = toppings self.slices_left = slices

Pizza

Page 80: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Pizza: def __init__(self, radius, toppings, slices=8): self.radius = radius self.toppings = toppings self.slices_left = slices

def eat_slice(self): if self.slices_left > 0: self.slices_left -= 1 else: print("Oh no! Out of pizza")

Pizza

Page 81: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Pizza: def __init__(self, radius, toppings, slices=8): self.radius = radius self.toppings = toppings self.slices_left = slices

def eat_slice(self): if self.slices_left > 0: self.slices_left -= 1 else: print("Oh no! Out of pizza")

def __repr__(self): return '{}" pizza'.format(self.radius)

Pizza

Page 82: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Pizza

Page 83: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)

Pizza

Page 84: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)

Pizza

Page 85: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

Pizza

Page 86: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

Pizza

Page 87: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)

Pizza

Page 88: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)# => <bound method Pizza.eat_slice of 14" Pizza>

Pizza

Page 89: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)# => <bound method Pizza.eat_slice of 14" Pizza>

Pizza

Page 90: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)# => <bound method Pizza.eat_slice of 14" Pizza>

method = p.eat_slice

Pizza

Page 91: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)# => <bound method Pizza.eat_slice of 14" Pizza>

method = p.eat_slicemethod.__self__ # => 14" Pizza

Pizza

Page 92: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)# => <bound method Pizza.eat_slice of 14" Pizza>

method = p.eat_slicemethod.__self__ # => 14" Pizzamethod.__func__ # => <function Pizza.eat_slice>

Pizza

Page 93: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)# => <bound method Pizza.eat_slice of 14" Pizza>

method = p.eat_slicemethod.__self__ # => 14" Pizzamethod.__func__ # => <function Pizza.eat_slice>

Pizza

Page 94: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

p = Pizza(14, ("Pepperoni", "Olives"), slices=12)print(Pizza.eat_slice)# => <function Pizza.eat_slice>

print(p.eat_slice)# => <bound method Pizza.eat_slice of 14" Pizza>

method = p.eat_slicemethod.__self__ # => 14" Pizzamethod.__func__ # => <function Pizza.eat_slice>

p.eat_slice() # Implicitly calls Pizza.eat_slice(p)

Pizza

Page 95: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class and Instance Variables

Page 96: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Class and Instance Variables

Page 97: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog:

Class and Instance Variables

Page 98: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: kind = 'Canine' # class variable shared by all instances

Class and Instance Variables

Page 99: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: kind = 'Canine' # class variable shared by all instances

def __init__(self, name): self.name = name # instance variable unique to each instance

Class and Instance Variables

Page 100: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: kind = 'Canine' # class variable shared by all instances

def __init__(self, name): self.name = name # instance variable unique to each instance

a = Dog('Astro')pb = Dog('Mr. Peanut Butter')

Class and Instance Variables

Page 101: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: kind = 'Canine' # class variable shared by all instances

def __init__(self, name): self.name = name # instance variable unique to each instance

a = Dog('Astro')pb = Dog('Mr. Peanut Butter')

a.kind # 'Canine' (shared by all dogs)pb.kind # 'Canine' (shared by all dogs)a.name # 'Astro' (unique to a)pb.name # 'Mr. Peanut Butter' (unique to pb)

Class and Instance Variables

Page 102: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Warning

Page 103: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog:

Warning

Page 104: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: tricks = []

Warning

Page 105: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: tricks = []

def __init__(self, name): self.name = name

Warning

Page 106: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: tricks = []

def __init__(self, name): self.name = name

def add_trick(self, trick): self.tricks.append(trick)

Warning

Page 107: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: tricks = []

def __init__(self, name): self.name = name

def add_trick(self, trick): self.tricks.append(trick)

Warning

What could go wrong?

Page 108: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Warning

Page 109: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')

Warning

Page 110: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')d.add_trick('roll over')e.add_trick('play dead')

Warning

Page 111: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')d.add_trick('roll over')e.add_trick('play dead')d.tricks # => ['roll over', 'play dead'] (shared value)

Warning

Page 112: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Did we Solve It?

Page 113: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog:

Did we Solve It?

Page 114: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: # Let's try a default argument! def __init__(self, name='', tricks=[]): self.name = name self.tricks = tricks

Did we Solve It?

Page 115: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: # Let's try a default argument! def __init__(self, name='', tricks=[]): self.name = name self.tricks = tricks

def add_trick(self, trick): self.tricks.append(trick)

Did we Solve It?

Page 116: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Hmm…

Page 117: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')

Hmm…

Page 118: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')d.add_trick('roll over')e.add_trick('play dead')

Hmm…

Page 119: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')d.add_trick('roll over')e.add_trick('play dead')d.tricks # => ['roll over', 'play dead'] (shared value)

Hmm…

Page 120: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Solution

Page 121: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog:

Solution

Page 122: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: def __init__(self, name): self.name = name self.tricks = [] # New list for each dog

Solution

Page 123: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: def __init__(self, name): self.name = name self.tricks = [] # New list for each dog

def add_trick(self, trick):

Solution

Page 124: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Dog: def __init__(self, name): self.name = name self.tricks = [] # New list for each dog

def add_trick(self, trick): self.tricks.append(trick)

Solution

Page 125: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Solution

Page 126: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')

Solution

Page 127: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')d.add_trick('roll over')e.add_trick('play dead')

Solution

Page 128: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

d = Dog('Fido')e = Dog('Buddy')d.add_trick('roll over')e.add_trick('play dead')d.tricks # => ['roll over']e.tricks # => ['play dead']

Solution

Page 129: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Privacy and Style

Page 130: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Keep an Eye Out!

Page 131: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Nothing is truly private!

Keep an Eye Out!

Page 132: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Nothing is truly private!Clients can modify anything

Keep an Eye Out!

Page 133: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Nothing is truly private!Clients can modify anything"With great power…"

Keep an Eye Out!

Page 134: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Stylistic Conventions

Page 135: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method's first parameter should always be self

Stylistic Conventions

Page 136: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method's first parameter should always be self Why? Explicitly differentiate instance vars from local vars

Stylistic Conventions

Page 137: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method's first parameter should always be self Why? Explicitly differentiate instance vars from local vars Recall: method calls implicitly provide the calling object

Stylistic Conventions

Page 138: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method's first parameter should always be self Why? Explicitly differentiate instance vars from local vars Recall: method calls implicitly provide the calling object as the first argument to the class function

Stylistic Conventions

Page 139: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method's first parameter should always be self Why? Explicitly differentiate instance vars from local vars Recall: method calls implicitly provide the calling object as the first argument to the class functionAttribute names prefixed with a leading underscore are

Stylistic Conventions

Page 140: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method's first parameter should always be self Why? Explicitly differentiate instance vars from local vars Recall: method calls implicitly provide the calling object as the first argument to the class functionAttribute names prefixed with a leading underscore are intended to be private (e.g. _spam)

Stylistic Conventions

Page 141: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A method's first parameter should always be self Why? Explicitly differentiate instance vars from local vars Recall: method calls implicitly provide the calling object as the first argument to the class functionAttribute names prefixed with a leading underscore are intended to be private (e.g. _spam)Use verbs for methods and nouns for data attributes

Stylistic Conventions

Page 142: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Inheritance

Page 143: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class DerivedClassName(BaseClassName): pass Any expression is fine

Note the parentheses

Page 144: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Single Inheritance

Page 145: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A class object 'remembers' its base class

Single Inheritance

Page 146: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A class object 'remembers' its base classIf you don't specify a base class, implicitly use object

Single Inheritance

Page 147: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A class object 'remembers' its base classIf you don't specify a base class, implicitly use objectMethod and attribute lookup begins in the derived class

Single Inheritance

Page 148: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A class object 'remembers' its base classIf you don't specify a base class, implicitly use objectMethod and attribute lookup begins in the derived class Proceeds down the chain of base classes

Single Inheritance

Page 149: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A class object 'remembers' its base classIf you don't specify a base class, implicitly use objectMethod and attribute lookup begins in the derived class Proceeds down the chain of base classesDerived methods override (shadow) base methods

Single Inheritance

Page 150: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

A class object 'remembers' its base classIf you don't specify a base class, implicitly use objectMethod and attribute lookup begins in the derived class Proceeds down the chain of base classesDerived methods override (shadow) base methods Like `virtual` in C++

Single Inheritance

Page 151: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Multiple Inheritance

"The Dreaded Diamond Pattern"

Page 152: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Derived(Base1, Base2, …, BaseN): pass

Multiple Inheritance

Page 153: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Derived(Base1, Base2, …, BaseN): pass

Base classes are separated by commas

Multiple Inheritance

Page 154: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Derived(Base1, Base2, …, BaseN): pass

Base classes are separated by commas

Multiple Inheritance

Order matters!

Page 155: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Attribute lookup is (almost) depth-first, left-to-right Officially, "C3 superclass linearization" More info on Wikipedia!Rarely usefulClasses have a hidden method .mro() Shows linearization of base classes

Attribute Resolution

Page 156: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class A: pass class B: pass class C: pass class D: pass class E: pass class K1(A, B, C): pass class K2(D, B, E): pass class K3(D, A): pass class Z(K1, K2, K3): pass

Z.mro() # [Z, K1, K2, K3, D, A, B, C, E, object]

Attribute Resolution In Action

Page 157: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Magic Methods

Page 158: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Magic Methods

dunderbar

Page 159: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Python uses __init__ to build classes

Magic Methods

dunderbar

Page 160: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Python uses __init__ to build classes We can supply our own __init__ for customization

Magic Methods

dunderbar

Page 161: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Python uses __init__ to build classes We can supply our own __init__ for customizationWhat else can we do? Can we make classes look like:

Magic Methods

dunderbar

Page 162: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Python uses __init__ to build classes We can supply our own __init__ for customizationWhat else can we do? Can we make classes look like: iterators?

Magic Methods

dunderbar

Page 163: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Python uses __init__ to build classes We can supply our own __init__ for customizationWhat else can we do? Can we make classes look like: iterators? sets? dictionaries?

Magic Methods

dunderbar

Page 164: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Python uses __init__ to build classes We can supply our own __init__ for customizationWhat else can we do? Can we make classes look like: iterators? sets? dictionaries? numbers?

Magic Methods

dunderbar

Page 165: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Python uses __init__ to build classes We can supply our own __init__ for customizationWhat else can we do? Can we make classes look like: iterators? sets? dictionaries? numbers? comparables?

Magic Methods

dunderbar

Page 166: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 167: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 168: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 169: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 170: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 171: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 172: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

x < y # => x.__lt__(y)

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 173: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

x < y # => x.__lt__(y)x + y # => x.__add__(y)

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 174: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

x < y # => x.__lt__(y)x + y # => x.__add__(y)iter(x) # => x.__iter__()

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 175: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

x < y # => x.__lt__(y)x + y # => x.__add__(y)iter(x) # => x.__iter__()next(x) # => x.__next__()

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 176: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

x < y # => x.__lt__(y)x + y # => x.__add__(y)iter(x) # => x.__iter__()next(x) # => x.__next__()len(x) # => x.__len__()

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 177: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

x < y # => x.__lt__(y)x + y # => x.__add__(y)iter(x) # => x.__iter__()next(x) # => x.__next__()len(x) # => x.__len__()el in x # => x.__contains__(el)

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 178: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

x = MagicClass()y = MagicClass()str(x) # => x.__str__()x == y # => x.__eq__(y)

x < y # => x.__lt__(y)x + y # => x.__add__(y)iter(x) # => x.__iter__()next(x) # => x.__next__()len(x) # => x.__len__()el in x # => x.__contains__(el)

Some Magic Methods

And so many more Link 1 Link 2 Link 3

Suppose MagicClass implements all of these magic methods

Page 179: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Example

Page 180: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point:

Example

Page 181: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0):

Example

Page 182: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x

Example

Page 183: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

Example

Page 184: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

Example

Page 185: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self):

Example

Page 186: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self): self.x, self.y = -self.y, self.x

Example

Page 187: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self): self.x, self.y = -self.y, self.x

Example

Page 188: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self): self.x, self.y = -self.y, self.x

def __add__(self, other):

Example

Page 189: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self): self.x, self.y = -self.y, self.x

def __add__(self, other): return Point(self.x + other.x, self.y + other.y)

Example

Page 190: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self): self.x, self.y = -self.y, self.x

def __add__(self, other): return Point(self.x + other.x, self.y + other.y)

Example

Page 191: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self): self.x, self.y = -self.y, self.x

def __add__(self, other): return Point(self.x + other.x, self.y + other.y)

def __str__(self):

Example

Page 192: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class Point: def __init__(self, x=0, y=0): self.x = x self.y = y

def rotate_90_CC(self): self.x, self.y = -self.y, self.x

def __add__(self, other): return Point(self.x + other.x, self.y + other.y)

def __str__(self): return "Point({0}, {1})".format(self.x, self.y)

Example

Page 193: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Example

Page 194: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()

Example

Page 195: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()print(o) # Point(0, 0)

Example

Page 196: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()print(o) # Point(0, 0)p1 = Point(3, 5)

Example

Page 197: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()print(o) # Point(0, 0)p1 = Point(3, 5)p2 = Point(4, 6)

Example

Page 198: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()print(o) # Point(0, 0)p1 = Point(3, 5)p2 = Point(4, 6)print(p1, p2) # Point(3, 5) Point(4, 6)

Example

Page 199: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()print(o) # Point(0, 0)p1 = Point(3, 5)p2 = Point(4, 6)print(p1, p2) # Point(3, 5) Point(4, 6)p1.rotate_90_CC()

Example

Page 200: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()print(o) # Point(0, 0)p1 = Point(3, 5)p2 = Point(4, 6)print(p1, p2) # Point(3, 5) Point(4, 6)p1.rotate_90_CC()print(p1) # Point(-5, 3)

Example

Page 201: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

o = Point()print(o) # Point(0, 0)p1 = Point(3, 5)p2 = Point(4, 6)print(p1, p2) # Point(3, 5) Point(4, 6)p1.rotate_90_CC()print(p1) # Point(-5, 3)print(p1 + p2) # Point(-1, 9)

Example

Page 202: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Case Study:Errors and Exceptions

Page 203: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Syntax Errors "Errors before execution"

Page 204: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>>

Syntax Errors "Errors before execution"

Page 205: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>>

Syntax Errors "Errors before execution"

while True print('Hello world')

Page 206: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> File "<stdin>", line 1 while True print('Hello world') ^SyntaxError: invalid syntax

Syntax Errors "Errors before execution"

while True print('Hello world')

Page 207: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> File "<stdin>", line 1 while True print('Hello world') ^SyntaxError: invalid syntax

Syntax Errors

Error is detected at the token preceding the arrow

"Errors before execution"

while True print('Hello world')

Page 208: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Exceptions "Errors during execution"

Page 209: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> 10 * (1/0)

Exceptions "Errors during execution"

Page 210: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> 10 * (1/0)Traceback (most recent call last): File "<stdin>", line 1ZeroDivisionError: division by zero

Exceptions "Errors during execution"

Page 211: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> 10 * (1/0)Traceback (most recent call last): File "<stdin>", line 1ZeroDivisionError: division by zero

>>> 4 + spam*3

Exceptions "Errors during execution"

Page 212: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> 10 * (1/0)Traceback (most recent call last): File "<stdin>", line 1ZeroDivisionError: division by zero

>>> 4 + spam*3Traceback (most recent call last): File "<stdin>", line 1NameError: name 'spam' is not defined

Exceptions "Errors during execution"

Page 213: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> 10 * (1/0)Traceback (most recent call last): File "<stdin>", line 1ZeroDivisionError: division by zero

>>> 4 + spam*3Traceback (most recent call last): File "<stdin>", line 1NameError: name 'spam' is not defined

>>> '2' + 2

Exceptions "Errors during execution"

Page 214: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> 10 * (1/0)Traceback (most recent call last): File "<stdin>", line 1ZeroDivisionError: division by zero

>>> 4 + spam*3Traceback (most recent call last): File "<stdin>", line 1NameError: name 'spam' is not defined

>>> '2' + 2Traceback (most recent call last): File "<stdin>", line 1TypeError: Can't convert 'int' object to str implicitly

Exceptions "Errors during execution"

Page 215: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

And More

Page 216: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

And More

SystemExit

KeyboardInterrupt

StopIteration

ZeroDivisionErrorAttributeError

IndexErrorKeyError

NameError

UnboundLocalError

OSError

NotImplementedError

SyntaxError

TypeError

Page 217: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

├── OSError │ ├── BlockingIOError │ ├── ChildProcessError │ ├── ConnectionError │ │ ├── BrokenPipeError │ │ ├── ConnectionAbortedError │ │ ├── ConnectionRefusedError │ │ └── ConnectionResetError │ ├── FileExistsError │ ├── FileNotFoundError │ ├── InterruptedError │ ├── IsADirectoryError │ ├── NotADirectoryError │ ├── PermissionError │ ├── ProcessLookupError │ └── TimeoutError ├── ReferenceError ├── RuntimeError │ └── NotImplementedError ├── SyntaxError │ └── IndentationError │ └── TabError

├── SystemError ├── TypeError ├── ValueError │ └── UnicodeError │ ├── UnicodeDecodeError │ ├── UnicodeEncodeError │ └── UnicodeTranslateError └─ Warning ├── DeprecationWarning ├── PendingDeprecationWarning ├── RuntimeWarning ├── SyntaxWarning ├── UserWarning ├── FutureWarning ├── ImportWarning ├── UnicodeWarning ├── BytesWarning └── ResourceWarning

BaseException ├── SystemExit ├── KeyboardInterrupt ├── GeneratorExit └── Exception ├── StopIteration ├── ArithmeticError │ ├── FloatingPointError │ ├── OverflowError │ └── ZeroDivisionError ├── AssertionError ├── AttributeError ├── BufferError ├── EOFError ├── ImportError ├── LookupError │ ├── IndexError │ └── KeyError ├── MemoryError ├── NameError │ └── UnboundLocalError ├── OSError

And Even MoreInheritance in Action!

Page 218: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Handling Exceptions

Page 219: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (broken)""" return int(input("Please enter a number: "))

What's Wrong?

Page 220: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (broken)""" return int(input("Please enter a number: "))

What's Wrong?

What happens if they enter a nonnumeric input?

Page 221: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Solution

Page 222: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int():

Solution

Page 223: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)"""

Solution

Page 224: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)""" while True:

Solution

Page 225: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)""" while True: try:

Solution

Page 226: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)""" while True: try: x = int(input("Please enter a number: "))

Solution

Page 227: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)""" while True: try: x = int(input("Please enter a number: ")) break

Solution

Page 228: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)""" while True: try: x = int(input("Please enter a number: ")) break except ValueError:

Solution

Page 229: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)""" while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! Invalid input. Try again...")

Solution

Page 230: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed)""" while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! Invalid input. Try again...") return x

Solution

Page 231: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Mechanics of try statement

Page 232: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

1) Attempt to execute the try clause

Mechanics of try statement

Page 233: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

1) Attempt to execute the try clause2a) If no exception occurs, skip the except clause. Done!

Mechanics of try statement

Page 234: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

1) Attempt to execute the try clause2a) If no exception occurs, skip the except clause. Done!2b) If an exception occurs, skip the rest of the try clause.

Mechanics of try statement

Page 235: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

1) Attempt to execute the try clause2a) If no exception occurs, skip the except clause. Done!2b) If an exception occurs, skip the rest of the try clause.2bi) If the exception's type matches (/ is a subclass of ) that named by except, then execute the except clause. Done!

Mechanics of try statement

Page 236: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

1) Attempt to execute the try clause2a) If no exception occurs, skip the except clause. Done!2b) If an exception occurs, skip the rest of the try clause.2bi) If the exception's type matches (/ is a subclass of ) that named by except, then execute the except clause. Done!2bii) Otherwise, hand off the exception to any outer try statements. If unhandled, halt execution. Done!

Mechanics of try statement

Page 237: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Conveniences

Page 238: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: distance = int(input("How far? ")) time = car.speed / distance car.drive(time)

Conveniences

Page 239: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: distance = int(input("How far? ")) time = car.speed / distance car.drive(time)except ValueError as e: print(e)

Conveniences

Bind a name to the exception instance

Page 240: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: distance = int(input("How far? ")) time = car.speed / distance car.drive(time)except ValueError as e: print(e)except ZeroDivisionError: print("Division by zero!")

Conveniences

Bind a name to the exception instance

Page 241: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: distance = int(input("How far? ")) time = car.speed / distance car.drive(time)except ValueError as e: print(e)except ZeroDivisionError: print("Division by zero!")except (NameError, AttributeError): print("Bad Car")

Conveniences

Catch multiple exceptions

Bind a name to the exception instance

Page 242: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: distance = int(input("How far? ")) time = car.speed / distance car.drive(time)except ValueError as e: print(e)except ZeroDivisionError: print("Division by zero!")except (NameError, AttributeError): print("Bad Car")except: print("Car unexpectedly crashed!")

Conveniences

Catch multiple exceptions

Bind a name to the exception instance

"Wildcard" catches everything

Page 243: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed?)""" while True: try: x = int(input("Please enter a number: ")) break except: print("Oops! Invalid input. Try again...") return x

Solution?

"I'll just catch 'em all!"

Page 244: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

def read_int(): """Reads an integer from the user (fixed?)""" while True: try: x = int(input("Please enter a number: ")) break except: print("Oops! Invalid input. Try again...") return x

Solution?

Oops! Now we can't CTRL+C to escape

"I'll just catch 'em all!"

Page 245: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Raising Exceptions

Page 246: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

The raise keyword

Page 247: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> raise NameError('Why hello there!')

The raise keyword

Page 248: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> raise NameError('Why hello there!')Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: Why hello there!

The raise keyword

Page 249: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> raise NameError('Why hello there!')Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: Why hello there!

>>> raise NameErrorTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError

The raise keyword

Page 250: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

>>> raise NameError('Why hello there!')Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: Why hello there!

>>> raise NameErrorTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError

The raise keyword

You can raise either instance objects or class objects

Page 251: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

raise within except clause

Page 252: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedError("TODO")except NotImplementedError: print('Looks like an exception to me!') raise

raise within except clause

Re-raises the currently active exception

Page 253: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedError("TODO")except NotImplementedError: print('Looks like an exception to me!') raise# Looks like an exception to me!# Traceback (most recent call last):# File "<stdin>", line 2, in <module># NotImplementedError: TODO

raise within except clause

Re-raises the currently active exception

Page 254: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Good Python: Using else

Page 255: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: ... except ...: ... else: do_something()

Code that executes if the try clause does not raise an exception

Why? Avoid accidentally catching an exception raised by something other than the code being protected

Page 256: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: update_the_database() except TransactionError: rollback() raise else: commit()

Example: Database Transactions

If the commit raises an exception, we might actually *want* to crash

Page 257: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Aside: Python Philosophy

Page 258: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Coding for the Common Case

Page 259: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Don't check if a file exists, then open it.

Coding for the Common Case

Page 260: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Don't check if a file exists, then open it. Just try to open it!

Coding for the Common Case

Page 261: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Don't check if a file exists, then open it. Just try to open it! Handle exceptional cases with an except clause (or two)

Coding for the Common Case

Page 262: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Don't check if a file exists, then open it. Just try to open it! Handle exceptional cases with an except clause (or two) (avoids race conditions too)

Coding for the Common Case

Page 263: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Don't check if a file exists, then open it. Just try to open it! Handle exceptional cases with an except clause (or two) (avoids race conditions too)Don't check if a queue is nonempty before popping

Coding for the Common Case

Page 264: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Don't check if a file exists, then open it. Just try to open it! Handle exceptional cases with an except clause (or two) (avoids race conditions too)Don't check if a queue is nonempty before popping Just try to pop the element!

Coding for the Common Case

Page 265: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Don't check if a file exists, then open it. Just try to open it! Handle exceptional cases with an except clause (or two) (avoids race conditions too)Don't check if a queue is nonempty before popping Just try to pop the element!

Coding for the Common Case

Page 266: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Good Python:Custom Exceptions

Page 267: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

class BadLoginError(Exception): """Raised when a user attempts to login with an incorrect password""" pass

Custom Exceptions

You can also override the default behavior of __init__, which binds all positional arguments to an args attribute

Don't misuse existing exceptions when the real error is something else!

Page 268: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Clean-Up Actions

Page 269: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

The finally clause

The finally clause is always executed before leaving the try/… block

Page 270: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try:

The finally clause

The finally clause is always executed before leaving the try/… block

Page 271: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedError

The finally clause

The finally clause is always executed before leaving the try/… block

Page 272: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedErrorfinally:

The finally clause

The finally clause is always executed before leaving the try/… block

Page 273: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedErrorfinally: print('Goodbye, world!')

The finally clause

The finally clause is always executed before leaving the try/… block

Page 274: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedErrorfinally: print('Goodbye, world!')

The finally clause

The finally clause is always executed before leaving the try/… block

Page 275: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedErrorfinally: print('Goodbye, world!')

# Goodbye, world!

The finally clause

The finally clause is always executed before leaving the try/… block

Page 276: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedErrorfinally: print('Goodbye, world!')

# Goodbye, world!# Traceback (most recent call last):

The finally clause

The finally clause is always executed before leaving the try/… block

Page 277: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedErrorfinally: print('Goodbye, world!')

# Goodbye, world!# Traceback (most recent call last):# File "<stdin>", line 2, in <module>

The finally clause

The finally clause is always executed before leaving the try/… block

Page 278: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

try: raise NotImplementedErrorfinally: print('Goodbye, world!')

# Goodbye, world!# Traceback (most recent call last):# File "<stdin>", line 2, in <module># NotImplementedError

The finally clause

The finally clause is always executed before leaving the try/… block

Page 279: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

How finally works

Page 280: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Always executed before leaving the try statement.

How finally works

Page 281: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Always executed before leaving the try statement.

How finally works

Page 282: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Always executed before leaving the try statement.

Unhandled exceptions (not caught, or raised in except)

How finally works

Page 283: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Always executed before leaving the try statement.

Unhandled exceptions (not caught, or raised in except) are re-raised after finally executes.

How finally works

Page 284: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Always executed before leaving the try statement.

Unhandled exceptions (not caught, or raised in except) are re-raised after finally executes.

How finally works

Page 285: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Always executed before leaving the try statement.

Unhandled exceptions (not caught, or raised in except) are re-raised after finally executes.

Also executed "on the way out" (break, continue, return)

How finally works

Page 286: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Note: with ... as ...

Surprisingly useful and flexible!

Page 287: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

# This is what enables us to use with ... as ...with open(filename) as f: raw = f.read()

Note: with ... as ...

Surprisingly useful and flexible!

Page 288: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

# This is what enables us to use with ... as ...with open(filename) as f: raw = f.read()# is (almost) equivalent tof = open(filename)f.__enter__()try: raw = f.read()finally: f.__exit__() # Closes the file

Note: with ... as ...

Surprisingly useful and flexible!

Page 289: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

The Road Ahead

Page 290: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Behind Us - The Python Language

Page 291: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Week 1 Python FundamentalsWeek 2 Data StructuresWeek 3 FunctionsWeek 4 Functional ProgrammingWeek 5 Object-Oriented Python

Behind Us - The Python Language

Page 292: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

The Road Ahead - Python Tools

Page 293: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Week 6 Standard LibraryWeek 7 Third-Party ToolsWeek 8 EcosystemWeek 9 Advanced TopicsWeek 10 Projects!

The Road Ahead - Python Tools

Page 294: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Next Time

Page 295: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Lab Time

Page 296: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Building Basic Classes

Lab Time

Page 297: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Building Basic ClassesFun with Inheritance

Lab Time

Page 298: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of

Building Basic ClassesFun with InheritanceMagic Methods a.k.a. 007

Lab Time

Page 299: Overview - Dipartimento di Informaticapages.di.unipi.it/corradini/Didattica/AP-17/SLIDES/PythonOOP.pdf · Recall: Programming Paradigms ... Object-Oriented Deal with collections of