Software Design Spring 2008 For today you should have: 1) read Chapter 10 2) worked on Homework 3 3) prepared for a quiz For lab: 1) finish Homework 3 2) read Chapter 9 3) start hw04 For Thursday: 1) read Chapter 11 2) work on Homework 4 Polymorphism ------------ A function that works with more than one type of parameter is polymorphic. Dynamic typing lends itself to polymorphism. In general: is all of the operations in a function work for a given type, then the function works for that type. In Python, all sequences support a common set of operations, so it is easy to write functions that work for strings, lists and (as we will see soon) tuples. Lists ----- Ways to create a list. 1) bracket operator: [], [1], [1, 2, 3] 2) list function: list('allen') this is why I don't recommend using list as a variable name 3) other functions that return lists: range(3) 4) slice operator: t[1:3], t[:] Indexing, slicing and len() are the same as for strings. The in operator works with lists. So do + and * The for loop works with lists: for var in t: print var List vocabulary --------------- compound object: sequence: index: element: item: slice: mutable: Lists are mutable ----------------- You can use the [] operator on the left side of an assignment: t = range(3) t[1] = 17 print t Now it really matters when two variables refer to the same list. Run: python lumpy_test.py Modify lumpy_test.py with this code: t1 = range(3) t2 = t1 t2[1] = 17 print t1 And then this: t1 = range(3) t2 = t1[:] t2[1] = 17 print t1 the is operator --------------- Try this: t1 = range(3) t2 = t1[:] print t1 == t2 print t1 is t2 These lists are equivalent but not the identical! print id(t1), id(t2) identity (shallow equality): same object equivalence (deep equality): same value lists as parameters ------------------- When objects are passed as arguments, they are passed by reference, which means that the parent function and the child function refer to the same object. Draw a stack diagram for this program: def deleteHead(t): del t[0] x = range(3) deleteHead(x) print x x and t are aliases for the same list object. changes made in deleteHead are reflected in __main__ (as intended) Now draw a stack diagram for this one: def badDeleteHead(t): t = t[1:] print t x = range(3) badDeleteHead(x) print x