Overview. Recap of FP Classes Instances Inheritance Exceptions

Size: px
Start display at page:

Download "Overview. Recap of FP Classes Instances Inheritance Exceptions"

Transcription

1 Overview Recap of FP Classes Instances Inheritance Exceptions

2 [len(s) for s in languages] ["python", "perl", "java", "c++"] map(len, languages) < 6, 4, 4, 3>

3 [num for num in fibs if is_even(num)] [1, 1, 2, 3, 5, 8, 13, 21, 34] filter(is_even, fibs) < 2, 8, 34 >

4 Function Definitions vs. Lambdas

5 Function Definitions vs. Lambdas def greet(): greet function def binds a function object print("hi!") bytecode to a name greet

6 Function Definitions vs. Lambdas def greet(): greet function def binds a function object print("hi!") bytecode to a name greet lambda val: val ** 2 lambda x, y: x * y lambda pair: pair[0] * pair[1] function bytecode <lambda> lambda only creates a function object

7 Function Definitions vs. Lambdas def greet(): greet function def binds a function object print("hi!") bytecode to a name greet lambda val: val ** 2 lambda x, y: x * y lambda pair: pair[0] * pair[1] function bytecode <lambda> lambda only creates a function object (lambda x: x > 3)(4) # => True

8 Our First Decorator def debug(function): def wrapper(*args, **kwargs): print("arguments:", args, kwargs) return function(*args, **kwargs) return def foo(a, b, c=1): return (a + b) * c

9 Object-Oriented Python

10 Recall: Programming Paradigms

11 Recall: Programming Paradigms Procedural Sequence of instructions that inform the computer what to do with the program's input Examples C Pascal Unix (sh)

12 Recall: Programming Paradigms Procedural Sequence of instructions that inform the computer what to do with the program's input Declarative Specification describes the problem to be solved, and language implementation figures out the details Examples C Pascal Unix (sh) Examples SQL Prolog

13 Recall: Programming Paradigms Procedural Sequence of instructions that inform the computer what to do with the program's input Declarative Specification describes the problem to be solved, and language implementation figures out the details Examples C Pascal Unix (sh) Examples SQL Prolog Object-Oriented Deal with collections of objects which maintain internal state and support methods that query or modify this internal state in some way. Examples Java Smalltalk

14 Recall: Programming Paradigms Procedural Sequence of instructions that inform the computer what to do with the program's input Declarative Specification describes the problem to be solved, and language implementation figures out the details Examples C Pascal Unix (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. Examples SQL Prolog Functional Decomposes into a set of functions, each of which solely takes inputs and produces outputs with no internal state. Examples Java Smalltalk Examples Haskell OCaml ML

15 Recall: Programming Paradigms Procedural Sequence of instructions that inform the computer what to do with the program's input Declarative Specification describes the problem to be solved, and language implementation figures out the details Examples C Pascal Unix (sh) Multi-Paradigm Supports several different paradigms, to be combined freely Examples SQL Prolog Object-Oriented Functional Deal with collections of objects which maintain internal Examples Decomposes into a set of functions, each of which solely state and support methods that query or modify this Scalatakes inputs and produces outputs with no internal state. internal state in some way. C++ Python Examples Java Smalltalk Examples Haskell OCaml ML

16 Objects, Names, Attributes

17 Some Definitions name

18 Some Definitions An object has identity name

19 Some Definitions An object has identity A name is a reference to an object name

20 Some Definitions An object has identity A name is a reference to an object A namespace is an associative mapping from names to objects name

21 Some Definitions An object has identity A name is a reference to an object A namespace is an associative mapping from names to objects An attribute is any name following a dot ('.') name type object identity

22 Classes

23 Class Definition Syntax

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

25 The class keyword introduces a new class defintion class ClassName: <statement> <statement>...

26 The class keyword introduces a new class defintion class ClassName: <statement> <statement>... Must be executed to have effect (like def)

27 Class Definitions

28 Class Definitions Statements are usually assignments or function definitions

29 Class Definitions Statements are usually assignments or function definitions Entering a class definition creates a new "namespace" - ish

30 Class Definitions Statements are usually assignments or function definitions Entering a class definition creates a new "namespace" - ish Exiting a class definition creates a class object

31 Class Definitions Statements are usually assignments or function definitions Entering a class definition creates a new "namespace" - ish Exiting a class definition creates a class object Defining a class == creating a class object (like int, str)

32 Class Definitions Statements are usually assignments or function definitions Entering a class definition creates a new "namespace" - ish Exiting a class definition creates a class object Defining a class == creating a class object (like int, str) Defining a class!= instantiating a class

33 Wait, What?

34 Class Objects vs. Instance Objects Defining a class creates a class object Supports attribute reference and instantiation Instantiating a class object creates an instance object Only supports attribute reference

35 Class Objects Support (1) attribute references and (2) instantation

36 Class Attribute References

37 Class Attribute References

38 Class Attribute References class MyClass: """A simple example class""" num = def greet(self): return "Hello world!"

39 Class Attribute References class MyClass: """A simple example class""" num = def greet(self): return "Hello world!" # Attribute References MyClass.num # => (int object) MyClass.greet # => <function f> (function object)

40 Class Attribute References class MyClass: """A simple example class""" num = def greet(self): return "Hello world!" # Attribute References MyClass.num # => (int object) MyClass.greet # => <function f> (function object) Warning! Class attributes can be written to by the client

41 Class Instantiation

42 Class Instantiation x = MyClass(args)

43 Class Instantiation No new x = MyClass(args)

44 Class Instantiation Classes are instantiated using parentheses No new and an argument list x = MyClass(args)

45 Class Instantiation Classes are instantiated using parentheses No new and an argument list x = MyClass(args) Instantiating a class constructs an instance object of that class object. In this case, x is an instance object of the MyClass class object

46 Custom Constructor using init

47 Custom Constructor using init class Complex: def init (self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart

48 Custom Constructor using init class Complex: def init (self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart Class instantiation calls the special method init if it exists

49 Custom Constructor using init 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) Class instantiation calls the special method init if it exists

50 Custom Constructor using init class Complex: def init (self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart Class instantiation calls the special method init if it exists # Make an instance object `c`! c = Complex(3.0, -4.5) c.real, c.imag # => (3.0, -4.5)

51 Custom Constructor using init class Complex: def init (self, realpart=0, imagpart=0): self.real = realpart self.imag = imagpart Class instantiation calls the special method init if it exists # Make an instance object `c`! c = Complex(3.0, -4.5) c.real, c.imag # => (3.0, -4.5) You can't overload init! Use keyword arguments or factory methods

52 Instance Objects Only support attribute references

53 Data Attributes = "instance variables" = "data members" Attribute references first search the instance's dict attribute, then the class object's

54 Data Attributes = "instance variables" = "data members" c = Complex(3.0, -4.5) Attribute references first search the instance's dict attribute, then the class object's

55 Data Attributes = "instance variables" = "data members" c = Complex(3.0, -4.5) c.real, c.imag # => (3.0, -4.5) Attribute references first search the instance's dict attribute, then the class object's

56 Data Attributes = "instance variables" = "data members" c = Complex(3.0, -4.5) c.real, c.imag # => (3.0, -4.5) Attribute references first search the instance's dict attribute, then the class object's

57 Data Attributes = "instance variables" = "data members" c = Complex(3.0, -4.5) c.real, c.imag # => (3.0, -4.5) c.real = -9.2 Attribute references first search the instance's dict attribute, then the class object's

58 Data Attributes = "instance variables" = "data members" c = Complex(3.0, -4.5) c.real, c.imag # => (3.0, -4.5) c.real = -9.2 c.imag = 4.1 Attribute references first search the instance's dict attribute, then the class object's

59 Setting Data Attributes

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

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

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

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

64 Setting Data Attributes # You can set attributes on instance (and class) objects # on the fly (we used this in the constructor!) c.counter = 1 while c.counter < 10: c.counter = x.counter * 2 print(c.counter) del c.counter # Leaves no trace # prints 1, 2, 4, 8 Setting attributes actually inserts into the instance object's dict attribute

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

66 Calling Methods

67 x = MyClass() Calling Methods

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

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

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

71 Calling Methods x = MyClass() x.greet() # 'Hello world!' # Weird... doesn't `greet` accept an argument? print(type(x.greet)) # method

72 Calling Methods x = MyClass() x.greet() # 'Hello world!' # Weird... doesn't `greet` accept an argument? print(type(x.greet)) # method print(type(myclass.greet)) # function

73 Calling Methods x = MyClass() x.greet() # 'Hello world!' # Weird... doesn't `greet` accept an argument? print(type(x.greet)) # method print(type(myclass.greet)) # function

74 Calling Methods x = MyClass() x.greet() # 'Hello world!' # Weird... doesn't `greet` accept an argument? print(type(x.greet)) # method print(type(myclass.greet)) # function print(x.num is MyClass.num) # True

75 Methods vs. Functions

76 Methods vs. Functions A method is a function bound to an object method (object, function) Methods calls invoke special semantics object.method(arguments) = function(object, arguments)

77 Pizza

78 class Pizza: Pizza

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

80 Pizza 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")

81 Pizza 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)

82 Pizza

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

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

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

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

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

88 Pizza 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>

89 Pizza 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>

90 Pizza 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

91 Pizza 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 method. self # => 14" Pizza

92 Pizza 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 method. self # => 14" Pizza method. func # => <function Pizza.eat_slice>

93 Pizza 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 method. self # => 14" Pizza method. func # => <function Pizza.eat_slice>

94 Pizza 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 method. self # => 14" Pizza method. func # => <function Pizza.eat_slice> p.eat_slice() # Implicitly calls Pizza.eat_slice(p)

95 Class and Instance Variables

96 Class and Instance Variables

97 class Dog: Class and Instance Variables

98 Class and Instance Variables class Dog: kind = 'Canine' # class variable shared by all instances

99 Class and Instance Variables class Dog: kind = 'Canine' # class variable shared by all instances def init (self, name): self.name = name # instance variable unique to each instance

100 Class and Instance Variables 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')

101 Class and Instance Variables 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)

102 Warning

103 class Dog: Warning

104 Warning class Dog: tricks = []

105 Warning class Dog: tricks = [] def init (self, name): self.name = name

106 Warning class Dog: tricks = [] def init (self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick)

107 Warning class Dog: tricks = [] def init (self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) What could go wrong?

108 Warning

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

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

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

112 Did we Solve It?

113 class Dog: Did we Solve It?

114 Did we Solve It? class Dog: # Let's try a default argument! def init (self, name='', tricks=[]): self.name = name self.tricks = tricks

115 Did we Solve It? 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)

116 Hmm

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

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

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

120 Solution

121 class Dog: Solution

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

123 Solution class Dog: def init (self, name): self.name = name self.tricks = [] # New list for each dog def add_trick(self, trick):

124 Solution 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)

125 Solution

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

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

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

129 Privacy and Style

130 Keep an Eye Out!

131 Nothing is truly private! Keep an Eye Out!

132 Keep an Eye Out! Nothing is truly private! Clients can modify anything

133 Keep an Eye Out! Nothing is truly private! Clients can modify anything "With great power "

134 Stylistic Conventions

135 Stylistic Conventions A method's first parameter should always be self

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

137 Stylistic Conventions 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

138 Stylistic Conventions 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

139 Stylistic Conventions 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 Attribute names prefixed with a leading underscore are

140 Stylistic Conventions 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 Attribute names prefixed with a leading underscore are intended to be private (e.g. _spam)

141 Stylistic Conventions 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 Attribute names prefixed with a leading underscore are intended to be private (e.g. _spam) Use verbs for methods and nouns for data attributes

142 Inheritance

143 Note the parentheses class DerivedClassName(BaseClassName): pass Any expression is fine

144 Single Inheritance

145 Single Inheritance A class object 'remembers' its base class

146 Single Inheritance A class object 'remembers' its base class If you don't specify a base class, implicitly use object

147 Single Inheritance A class object 'remembers' its base class If you don't specify a base class, implicitly use object Method and attribute lookup begins in the derived class

148 Single Inheritance A class object 'remembers' its base class If you don't specify a base class, implicitly use object Method and attribute lookup begins in the derived class Proceeds down the chain of base classes

149 Single Inheritance A class object 'remembers' its base class If you don't specify a base class, implicitly use object Method and attribute lookup begins in the derived class Proceeds down the chain of base classes Derived methods override (shadow) base methods

150 Single Inheritance A class object 'remembers' its base class If you don't specify a base class, implicitly use object Method and attribute lookup begins in the derived class Proceeds down the chain of base classes Derived methods override (shadow) base methods Like `virtual` in C++

151 Multiple Inheritance "The Dreaded Diamond Pattern"

152 Multiple Inheritance class Derived(Base1, Base2,, BaseN): pass

153 Multiple Inheritance Base classes are separated by commas class Derived(Base1, Base2,, BaseN): pass

154 Multiple Inheritance Base classes are separated by commas class Derived(Base1, Base2,, BaseN): pass Order matters!

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

156 Attribute Resolution In Action 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]

157 Magic Methods

158 Magic Methods dunderbar

159 Magic Methods Python uses init to build classes dunderbar

160 Magic Methods Python uses init to build classes We can supply our own init for customization dunderbar

161 Magic Methods Python uses init to build classes We can supply our own init for customization What else can we do? Can we make classes look like: dunderbar

162 Magic Methods Python uses init to build classes We can supply our own init for customization What else can we do? Can we make classes look like: iterators? dunderbar

163 Magic Methods Python uses init to build classes We can supply our own init for customization What else can we do? Can we make classes look like: iterators? dunderbar sets? dictionaries?

164 Magic Methods Python uses init to build classes We can supply our own init for customization What else can we do? Can we make classes look like: iterators? dunderbar sets? dictionaries? numbers?

165 Magic Methods Python uses init to build classes We can supply our own init for customization What else can we do? Can we make classes look like: iterators? dunderbar sets? dictionaries? numbers? comparables?

166 Some Magic Methods Suppose MagicClass implements all of these magic methods And so many more Link 1 Link 2 Link 3

167 Some Magic Methods x = MagicClass() Suppose MagicClass implements all of these magic methods And so many more Link 1 Link 2 Link 3

168 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods And so many more Link 1 Link 2 Link 3

169 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) # => x. str () And so many more Link 1 Link 2 Link 3

170 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) And so many more Link 1 Link 2 Link 3

171 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) And so many more Link 1 Link 2 Link 3

172 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) x < y # => x. lt (y) And so many more Link 1 Link 2 Link 3

173 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) x < y x + y # => x. lt (y) # => x. add (y) And so many more Link 1 Link 2 Link 3

174 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) x < y x + y # => x. lt (y) # => x. add (y) iter(x) # => x. iter () And so many more Link 1 Link 2 Link 3

175 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) x < y x + y # => x. lt (y) # => x. add (y) iter(x) # => x. iter () next(x) # => x. next () And so many more Link 1 Link 2 Link 3

176 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) x < y x + y # => x. lt (y) # => x. add (y) iter(x) # => x. iter () next(x) # => x. next () And so many more len(x) # => x. len () Link 1 Link 2 Link 3

177 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) x < y x + y # => x. lt (y) # => x. add (y) iter(x) # => x. iter () next(x) # => x. next () And so many more len(x) # => x. len () Link 1 el in x # => x. contains (el) Link 2 Link 3

178 Some Magic Methods x = MagicClass() y = MagicClass() Suppose MagicClass implements all of these magic methods str(x) x == y # => x. str () # => x. eq (y) x < y x + y # => x. lt (y) # => x. add (y) iter(x) # => x. iter () next(x) # => x. next () And so many more len(x) # => x. len () Link 1 el in x # => x. contains (el) Link 2 Link 3

179 Example

180 class Point: Example

181 Example class Point: def init (self, x=0, y=0):

182 Example class Point: def init (self, x=0, y=0): self.x = x

183 Example class Point: def init (self, x=0, y=0): self.x = x self.y = y

184 Example class Point: def init (self, x=0, y=0): self.x = x self.y = y

185 Example class Point: def init (self, x=0, y=0): self.x = x self.y = y def rotate_90_cc(self):

186 Example 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

187 Example 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

188 Example 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):

189 Example 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)

190 Example 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)

191 Example 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):

192 Example 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)

193 Example

194 o = Point() Example

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

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

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

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

199 Example 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()

200 Example 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)

201 Example 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)

202 Case Study: Errors and Exceptions

203 Syntax Errors "Errors before execution"

204 Syntax Errors "Errors before execution" >>>

205 Syntax Errors "Errors before execution" >>> while True print('hello world')

206 Syntax Errors "Errors before execution" >>> while True print('hello world') File "<stdin>", line 1 while True print('hello world') ^ SyntaxError: invalid syntax

207 Syntax Errors "Errors before execution" >>> while True print('hello world') File "<stdin>", line 1 while True print('hello world') ^ Error is detected at the token preceding the arrow SyntaxError: invalid syntax

208 Exceptions "Errors during execution"

209 Exceptions "Errors during execution" >>> 10 * (1/0)

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

211 Exceptions "Errors during execution" >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1 ZeroDivisionError: division by zero >>> 4 + spam*3

212 Exceptions "Errors during execution" >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1 ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1 NameError: name 'spam' is not defined

213 Exceptions "Errors during execution" >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1 ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1 NameError: name 'spam' is not defined >>> '2' + 2

214 Exceptions "Errors during execution" >>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1 ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1 NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1 TypeError: Can't convert 'int' object to str implicitly

215 And More

216 And More KeyboardInterrupt UnboundLocalError SystemExit StopIteration SyntaxError ZeroDivisionError AttributeError KeyError IndexError NotImplementedError TypeError OSError NameError

217 BaseException SystemExit KeyboardInterrupt GeneratorExit Exception StopIteration ArithmeticError FloatingPointError OverflowError ZeroDivisionError AssertionError AttributeError BufferError EOFError ImportError LookupError IndexError KeyError MemoryError NameError UnboundLocalError OSError OSError BlockingIOError ChildProcessError ConnectionError SystemError TypeError ValueError UnicodeError BrokenPipeError UnicodeDecodeError ConnectionAbortedError ConnectionRefusedError UnicodeEncodeError UnicodeTranslateError ConnectionResetError Warning FileExistsError DeprecationWarning FileNotFoundError PendingDeprecationWarning InterruptedError RuntimeWarning IsADirectoryError SyntaxWarning NotADirectoryError UserWarning PermissionError FutureWarning ProcessLookupError ImportWarning TimeoutError UnicodeWarning ReferenceError BytesWarning RuntimeError ResourceWarning NotImplementedError SyntaxError IndentationError TabError And Even More Inheritance in Action!

218 Handling Exceptions

219 What's Wrong? def read_int(): """Reads an integer from the user (broken)""" return int(input("please enter a number: "))

220 What's Wrong? def read_int(): """Reads an integer from the user (broken)""" return int(input("please enter a number: ")) What happens if they enter a nonnumeric input?

221 Solution

222 def read_int(): Solution

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

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

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

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

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

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

229 Solution 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...")

230 Solution 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

231 Mechanics of try statement

232 Mechanics of try statement 1) Attempt to execute the try clause

233 Mechanics of try statement 1) Attempt to execute the try clause 2a) If no exception occurs, skip the except clause. Done!

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

235 Mechanics of try statement 1) Attempt to execute the try clause 2a) 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!

236 Mechanics of try statement 1) Attempt to execute the try clause 2a) 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!

237 Conveniences

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

239 Conveniences try: distance = int(input("how far? ")) time = car.speed / distance car.drive(time) except ValueError as e: Bind a name to the exception instance print(e)

240 Conveniences try: distance = int(input("how far? ")) time = car.speed / distance car.drive(time) except ValueError as e: Bind a name to the exception instance print(e) except ZeroDivisionError: print("division by zero!")

241 Conveniences try: distance = int(input("how far? ")) time = car.speed / distance car.drive(time) except ValueError as e: Bind a name to the exception instance print(e) except ZeroDivisionError: print("division by zero!") Catch multiple exceptions except (NameError, AttributeError): print("bad Car")

242 Conveniences try: distance = int(input("how far? ")) time = car.speed / distance car.drive(time) except ValueError as e: Bind a name to the exception instance print(e) except ZeroDivisionError: print("division by zero!") Catch multiple exceptions except (NameError, AttributeError): print("bad Car") except: "Wildcard" catches everything print("car unexpectedly crashed!")

243 Solution? def read_int(): """Reads an integer from the user (fixed?)""" while True: try: x = int(input("please enter a number: ")) break except: "I'll just catch 'em all!" return x print("oops! Invalid input. Try again...")

244 Solution? def read_int(): """Reads an integer from the user (fixed?)""" while True: try: x = int(input("please enter a number: ")) break except: "I'll just catch 'em all!" return x print("oops! Invalid input. Try again...") Oops! Now we can't CTRL+C to escape

245 Raising Exceptions

246 The raise keyword

247 The raise keyword >>> raise NameError('Why hello there!')

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

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

250 The raise keyword >>> raise NameError('Why hello there!') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: Why hello there! You can raise either instance objects or class objects >>> raise NameError Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError

251 raise within except clause

252 raise within except clause try: raise NotImplementedError("TODO") except NotImplementedError: print('looks like an exception to me!') raise Re-raises the currently active exception

253 raise within except clause try: raise NotImplementedError("TODO") except NotImplementedError: print('looks like an exception to me!') raise Re-raises the currently active exception # Looks like an exception to me! # Traceback (most recent call last): # File "<stdin>", line 2, in <module> # NotImplementedError: TODO

254 Good Python: Using else

255 try:... except...:... else: Code that executes if the try clause does not raise an exception do_something() Why? Avoid accidentally catching an exception raised by something other than the code being protected

256 Example: Database Transactions try: update_the_database() except TransactionError: rollback() raise else: commit() If the commit raises an exception, we might actually *want* to crash

257 Aside: Python Philosophy

258 Coding for the Common Case

259 Coding for the Common Case Don't check if a file exists, then open it.

260 Coding for the Common Case Don't check if a file exists, then open it. Just try to open it!

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

262 Coding for the Common Case 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)

263 Coding for the Common Case 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

264 Coding for the Common Case 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!

265 Coding for the Common Case 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!

266 Good Python: Custom Exceptions

267 Custom Exceptions class BadLoginError(Exception): """Raised when a user attempts to login with an incorrect password""" pass Don't misuse existing exceptions when the real error is something else! You can also override the default behavior of init, which binds all positional arguments to an args attribute

268 Clean-Up Actions

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

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

271 The finally clause try: raise NotImplementedError The finally clause is always executed before leaving the try/ block

272 The finally clause try: raise NotImplementedError finally: The finally clause is always executed before leaving the try/ block

273 The finally clause try: raise NotImplementedError finally: print('goodbye, world!') The finally clause is always executed before leaving the try/ block

274 The finally clause try: raise NotImplementedError finally: print('goodbye, world!') The finally clause is always executed before leaving the try/ block

275 The finally clause try: raise NotImplementedError finally: print('goodbye, world!') The finally clause is always executed before leaving the try/ block # Goodbye, world!

276 The finally clause try: raise NotImplementedError finally: print('goodbye, world!') The finally clause is always executed before leaving the try/ block # Goodbye, world! # Traceback (most recent call last):

277 The finally clause try: raise NotImplementedError finally: print('goodbye, world!') The finally clause is always executed before leaving the try/ block # Goodbye, world! # Traceback (most recent call last): # File "<stdin>", line 2, in <module>

278 The finally clause try: raise NotImplementedError finally: print('goodbye, world!') The finally clause is always executed before leaving the try/ block # Goodbye, world! # Traceback (most recent call last): # File "<stdin>", line 2, in <module> # NotImplementedError

279 How finally works

280 How finally works Always executed before leaving the try statement.

281 How finally works Always executed before leaving the try statement.

282 How finally works Always executed before leaving the try statement. Unhandled exceptions (not caught, or raised in except)

283 How finally works Always executed before leaving the try statement. Unhandled exceptions (not caught, or raised in except) are re-raised after finally executes.

284 How finally works Always executed before leaving the try statement. Unhandled exceptions (not caught, or raised in except) are re-raised after finally executes.

285 How finally works 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)

286 Note: with... as... Surprisingly useful and flexible!

287 Note: with... as... # This is what enables us to use with... as... with open(filename) as f: raw = f.read() Surprisingly useful and flexible!

288 Note: with... as... # This is what enables us to use with... as... with open(filename) as f: raw = f.read() Surprisingly useful and flexible! # is (almost) equivalent to f = open(filename) f. enter () try: raw = f.read() finally: f. exit () # Closes the file

289 The Road Ahead

290 Behind Us - The Python Language

291 Behind Us - The Python Language Week 1 Python Fundamentals Week 2 Data Structures Week 3 Functions Week 4 Functional Programming Week 5 Object-Oriented Python

292 The Road Ahead - Python Tools

293 The Road Ahead - Python Tools Week 6 Standard Library Week 7 Third-Party Tools Week 8 Ecosystem Week 9 Advanced Topics Week 10 Projects!

294 Next Time

295 Lab Time

296 Lab Time Building Basic Classes

297 Lab Time Building Basic Classes Fun with Inheritance

298 Lab Time Building Basic Classes Fun with Inheritance Magic Methods a.k.a. 007

299

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

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

Exceptions CS GMU

Exceptions CS GMU Exceptions CS 112 @ GMU Exceptions When an unrecoverable action takes place, normal control flow is abandoned: an exception value crashes outwards until caught. various types of exception values can be

More information

Python File Modes. Mode Description. Open a file for reading. (default)

Python File Modes. Mode Description. Open a file for reading. (default) UNIT V FILES, MODULES, PACKAGES Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative

More information

Programming Paradigms

Programming Paradigms Programming Paradigms Procedural Sequence of instructions that inform the computer what to do with the program's input Declarative Specification describes the problem to be solved, and language implementation

More information

LECTURE 6. Advanced Functions and OOP

LECTURE 6. Advanced Functions and OOP LECTURE 6 Advanced Functions and OOP FUNCTIONS Before we start, let s talk about how name resolution is done in Python: When a function executes, a new namespace is created (locals). New namespaces can

More information

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

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information

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

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria CSE 399-004: Python Programming Lecture 5: Course project and Exceptions February 12, 2007 Announcements Still working on grading Homeworks 3 and 4 (and 2 ) Homework 5 will be out by tomorrow morning I

More information

Exception Handling and Debugging

Exception Handling and Debugging Exception Handling and Debugging Any good program makes use of a language s exception handling mechanisms. There is no better way to frustrate an end-user then by having them run into an issue with your

More information

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : }

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : } Chapter 8 More Data Structures We have seen the list data structure and its uses. We will now examine two, more advanced data structures: the set and the dictionary. In particular, the dictionary is an

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

Lecture #12: Quick: Exceptions and SQL

Lecture #12: Quick: Exceptions and SQL UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 16 Classes Prof. Jeremy Dixon Based on slides from http://www.csee.umbc.edu/courses/691p/notes/python/python3.ppt Last Class We Covered Review of Functions

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class myclass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = myclass('student', 'teacher')

More information

bioengineering-book Documentation

bioengineering-book Documentation bioengineering-book Documentation Release 0.1 Thiranja Prasad Babarenda Gamage Sep 15, 2017 Contents 1 Introduction 3 2 Linux FAQ 5 2.1 Find files in a terminal..........................................

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class MyClass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = MyClass('student', 'teacher')

More information

Exception Handling. Genome 559

Exception Handling. Genome 559 Exception Handling Genome 559 Review - classes Use your own classes to: - package together related data - conceptually organize your code - force a user to conform to your expectations Class constructor:

More information

LECTURE 6. Advanced Functions and OOP

LECTURE 6. Advanced Functions and OOP LECTURE 6 Advanced Functions and OOP FUNCTIONS Before we start, let s talk about how name resolution is done in Python: When a function executes, a new namespace is created (locals). New namespaces can

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

Exceptions & error handling in Python 2 and Python 3

Exceptions & error handling in Python 2 and Python 3 Exceptions & error handling in Python 2 and Python 3 http://www.aleax.it/pycon16_eh.pdf 2016 Google -- aleax@google.com 1 Python in a Nutshell 3rd ed Chapter 5 of Early Release e-book version 50% off:

More information

SBT 645 Introduction to Scientific Computing in Sports Science #6

SBT 645 Introduction to Scientific Computing in Sports Science #6 SBT 645 Introduction to Scientific Computing in Sports Science #6 SERDAR ARITAN serdar.aritan@hacettepe.edu.tr Biyomekanik Araştırma Grubu www.biomech.hacettepe.edu.tr Spor Bilimleri Fakültesi www.sbt.hacettepe.edu.tr

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Week 2. Classes and Objects

Week 2. Classes and Objects Week 2 Classes and Objects Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

More information

CS 11 python track: lecture 4

CS 11 python track: lecture 4 CS 11 python track: lecture 4 Today: More odds and ends assertions "print >>" syntax more on argument lists functional programming tools list comprehensions More on exception handling More on object-oriented

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

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

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3] What is an Exception? Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem An exception is an abnormal condition (and thus rare)

More information

Modules and scoping rules

Modules and scoping rules C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded

More information

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

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

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo) 61A Lecture 25 Announcements Pairs Review Pairs and Lists In the late 1950s, computer scientists used confusing names cons: Two-argument procedure that creates a pair car: Procedure that returns the first

More information

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

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Chapter 9: Dealing with Errors

Chapter 9: Dealing with Errors Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple

More information

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014 Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014 Intermission Rant about the history of this talk and why this topic matters. Python decorator syntax @function_wrapper def

More information

Lecture 18. Classes and Types

Lecture 18. Classes and Types Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2 Basic Concepts Computer Science Computer - Science - Programming history Algorithms Pseudo code 2013 Andrew Case 2 Basic Concepts Computer Science Computer a machine for performing calculations Science

More information

Getting Started Values, Expressions, and Statements CS GMU

Getting Started Values, Expressions, and Statements CS GMU Getting Started Values, Expressions, and Statements CS 112 @ GMU Topics where does code go? values and expressions variables and assignment 2 where does code go? we can use the interactive Python interpreter

More information

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

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING (download slides and.py files follow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1 OBJECTS Python supports many different kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13]

More information

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

Exceptions. raise type(message) raise Exception(message) Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

More information

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

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013 CS61A Lecture 32 Amir Kamil UC Berkeley April 5, 2013 Announcements Hog revisions due Monday HW10 due Wednesday Make sure to fill out survey on Piazza We need to schedule alternate final exam times for

More information

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace ? User Defined Types Babes-Bolyai University arthur@cs.ubbcluj.ro Overview? 1? 2 3 ? NB! Types classify values. A type denotes a domain (a set of values) operations on those values. ? Object oriented programming

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

Object Oriented Programming #10

Object Oriented Programming #10 Object Oriented Programming #10 Serdar ARITAN Biomechanics Research Group, Faculty of Sports Sciences, and Department of Computer Graphics Hacettepe University, Ankara, Turkey 1 Simple programming tasks

More information

CS Lecture 26: Grab Bag. Announcements

CS Lecture 26: Grab Bag. Announcements CS 1110 Lecture 26: Grab Bag Announcements The End is Nigh! 1. Next (last) lecture will be recap and final exam review 2. A5 due Wednesday night 3. Final exam 7pm Thursday May 15 in Barton Hall (East section)

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

Review 3. Exceptions and Try-Except Blocks

Review 3. Exceptions and Try-Except Blocks Review 3 Exceptions and Try-Except Blocks What Might You Be Asked Create your own Exception class Write code to throw an exception Follow the path of a thrown exception Requires understanding of try-except

More information

Software Development Python (Part B)

Software Development Python (Part B) Software Development Python (Part B) Davide Balzarotti Eurecom 1 List Comprehension It is a short way to construct a list based on the content of other existing lists Efficient Elegant Concise List comprehensions

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object-Oriented Programming Robert Rand University of Pennsylvania February 10, 2016 Robert Rand (University of Pennsylvania) CIS 192 February 10, 2016 1 / 25 Outline 1 Object

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Material from Carlos G. Oliver, Christopher J.F. Cameron October 12, 2018 1/31 Reminder CSUS is holding a midterm review session on Monday, October 15th, from 6-9pm.

More information

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes Class definition F21SC Industrial Programming: Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2014/15 Class definition uses familiar

More information

Programming I. Course 9 Introduction to programming

Programming I. Course 9 Introduction to programming Programming I Course 9 Introduction to programming What we talked about? Modules List Comprehension Generators Recursive Functions Files What we talk today? Object Oriented Programming Classes Objects

More information

61A Lecture 25. Friday, October 28

61A Lecture 25. Friday, October 28 61A Lecture 25 Friday, October 2 From Last Time: Adjoining to a Tree Set 5 9 7 3 9 7 11 1 7 11 Right! Left! Right! Stop! 5 9 7 3 9 7 11 1 7 11 2 From the Exam: Pruned Trees a b c d (a,b) (a,c) (a,d) pruned

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming ECE 364 Software Engineering Tools Laboratory Lecture 7 Python: Object Oriented Programming 1 Lecture Summary Object Oriented Programming Concepts Object Oriented Programming in Python 2 Object Oriented

More information

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Introduction Robert Rand University of Pennsylvania September 16, 2015 Robert Rand (University of Pennsylvania) CIS 192 September 16, 2015 1 / 21 Outline 1 Object Orientation

More information

F21SC Industrial Programming: Python: Classes and Exceptions

F21SC Industrial Programming: Python: Classes and Exceptions F21SC Industrial Programming: Python: Classes and Exceptions Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

More information

CS 11 python track: lecture 2

CS 11 python track: lecture 2 CS 11 python track: lecture 2 Today: Odds and ends Introduction to object-oriented programming Exception handling Odds and ends List slice notation Multiline strings Docstrings List slices (1) a = [1,

More information

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Functions

More information

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1 The Three Rules Chapter 1 Beginnings Rule 1: Think before you program Rule 2: A program is a human-readable essay on problem solving that also executes on a computer Rule 3: The best way to improve your

More information

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern CSE 399-004: Python Programming Lecture 12: Decorators April 9, 200 http://www.seas.upenn.edu/~cse39904/ Announcements Projects (code and documentation) are due: April 20, 200 at pm There will be informal

More information

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods Today CSE341: Programming Languages Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins Alan Borning Spring 2018 Dynamic dispatch aka late binding aka virtual method calls Call to self.m2() in

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Python Decorators. Chris Calloway

Python Decorators. Chris Calloway Python Decorators Chris Calloway What is a Decorator? An object. What is a Decorator? An object. A callable object which is passed a function reference as its sole argument. What is a Decorator? An object.

More information

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Classes Dr. David Koop Tuple, List, Dictionary, or Set? [1,2,"abc"] 2 Tuple, List, Dictionary, or Set? {"a", 1, 2} 3 Tuple, List, Dictionary, or Set? {} 4 Tuple,

More information

CSC148: Week 2

CSC148: Week 2 CSC148: Week 2 http://www.cdf.utoronto.ca/~csc148h/summer/ Sophia Huynh Summer 2018 1 Annoucements Ex1 due tonight @ 11PM Ex2 will be released tonight No lab next week "Lab 2" will be released tonight

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

Lecture 8: A cure for what ails you

Lecture 8: A cure for what ails you Lecture 8: A cure for what ails you When human beings acquired language, we learned not just how to listen but how to speak. When we gained literacy, we learned not just how to read but how to write.

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Object-Oriented Python

Object-Oriented Python Object-Oriented Python Everything is an object. Every object has a value. a type. an identity. a namespace. CS105 Python def initstudent(student, eid): global A class is like a namespace. CS105 Python

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

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

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce Lecture 38: Python CS 51G Spring 2018 Kim Bruce Announcements Test program 2 Academic Honesty Guidelines! Quiz Friday (Strings & Streams) Lecture Friday will be in lab Write searches and sorts in Python

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

More information

Python for Finance. Advanced Features. Andras Niedermayer

Python for Finance. Advanced Features. Andras Niedermayer Python for Finance Advanced Features Andras Niedermayer Objects of Interest object oriented programming (Wikipedia) Definition (Object-oriented Programming) Object-oriented programming (OOP) is a programming

More information

Class Design (Section 9 of 17)

Class Design (Section 9 of 17) the architects themselves came in to explain the advantages of both designs Class Design (Section 9 of 17) In the previous sections we have used existing classes that enable us to be able to write functions

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

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

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013 61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS Steven Tang and Eric Tzeng July 23, 2013 Announcements Regrades for project 1 composition scores, due by next Monday See Piazza post for more details Midterm

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Python for Astronomers. Errors and Exceptions

Python for Astronomers. Errors and Exceptions Python for Astronomers Errors and Exceptions Exercise Create a module textstat that contains the functions openfile(filename, readwrite=false): opens the specified file (readonly or readwrite) and returns

More information

CSCE 110: Programming I

CSCE 110: Programming I CSCE 110: Programming I Sample Questions for Exam #1 February 17, 2013 Below are sample questions to help you prepare for Exam #1. Make sure you can solve all of these problems by hand. For most of the

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Arrays Dr. David Koop Class Example class Rectangle: def init (self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h def set_corner(self, x, y): self.x =

More information