Software Design Spring 2008 For today you should have: 1) read Chapter 17 2) worked on Homework 6 For lab Tuesday: 1) finish Homework 6 2) read Chapter 18 For Thursday you should: 1) work on Homework 7 2) prepare for a quiz Exercise -------- Write a definition for a class named Kangaroo with the following methods: 1) An __init__ method that initializes an attribute named pouch_contents to an empty list. 2) A method named put_in_pouch that takes an object of any type and adds it to pouch_contents. Then write a couple of lines of code that test your methods by creating two Kangaroo objects, assigning them to variables named kanga and roo, and then adding roo to the contents of kanga's pouch. If you have time, draw an object diagram showing these objects and their attributes. Or get Lumpy to draw it for you. class Kangaroo: def __init__(self): self.pouch_contents = [] def put_in_pouch(self, obj): self.pouch_contents.append(obj) kanga = Kangaroo() # remember lower case for variable names, roo = Kangaroo() # upper case for classes. kanga.put_in_pouch(roo) Optional parameters ------------------- When you define a function, you can provide default values for the parameters: class Point: def __init__(self, x=0, y=0): self.x = x self.y = y Then when you call the function, you can optionally override the defaults: p1 = Point() # creates the point (0,0) p2 = Point(5) # overrides x but not y p3 = Point(5, 7) # overrides x and y In the previous three examples, the arguments are positional; they get assigned to the parameters in order. You can also provide keyword arguments that include the name of the parameter: p4 = Point(y=7) # overrides y but not x If you have positional arguments and keyword arguments, the positional arguments have to come first. p5 = Point(5, y=7) # good p6 = Point(y=7, 5) # bad try...except ------------ Structurally similar to if...else. try: d[key] += 1 except: d[key] = 1 If an exception (run-time error) occurs, the try clause is aborted and the except clause is executed. If the try clause executes without an exception, the except clause is skipped. DANGER: if you use a try statement to handle a particular, expected error, be careful not to "smother" an unexpected error. Partial solution: specify the type of exception to catch. try: d[key] += 1 except KeyError: d[key] = 1 How do you learn the names of the exceptions? Handling unusual conditions --------------------------- We have now seen three ways of dealing with unusual conditions (discussion based on the Python Cookbook, Alex Martelli) LBYL (look before you leap): if key in d: d[key] += 1 else: d[key] = 1 EAFTP (easier to ask forgiveness than permission): try: d[key] += 1 except KeyError: d[key] = 1 HDC (homogenize different cases): d[key] = d.get(key, 0) + 1 What are the pros and cons?