|
| 1 | +""" |
| 2 | +
|
| 3 | +This program is part of an exercise in |
| 4 | +Think Python: An Introduction to Software Design |
| 5 | +Allen B. Downey |
| 6 | +
|
| 7 | +This program explains and corrects a bug in BadKangaroo.py. |
| 8 | +Before reading this, you should try to debug BadKangaroo. |
| 9 | +
|
| 10 | +""" |
| 11 | + |
| 12 | +class Kangaroo(object): |
| 13 | + """a Kangaroo is a marsupial""" |
| 14 | + |
| 15 | + def __init__(self, contents=[]): |
| 16 | + # The problem is the default value for contents. |
| 17 | + # Default values get evaluated ONCE, when the function |
| 18 | + # is defined; they don't get evaluated again when the |
| 19 | + # function is called. |
| 20 | + |
| 21 | + # In this case that means that when __init__ is defined, |
| 22 | + # [] gets evaluated and contents gets a reference to |
| 23 | + # an empty list. |
| 24 | + |
| 25 | + # After that, every Kangaroo that gets the default |
| 26 | + # value get a reference to THE SAME list. If any |
| 27 | + # Kangaroo modifies this shared list, they all see |
| 28 | + # the change. |
| 29 | + |
| 30 | + # The next version of __init__ shows an idiomatic way |
| 31 | + # to avoid this problem. |
| 32 | + self.pouch_contents = contents |
| 33 | + |
| 34 | + def __init__(self, contents=None): |
| 35 | + # In this version, the default value is None. When |
| 36 | + # __init__ runs, it checks the value of contents and, |
| 37 | + # if necessary, creates a new empty list. That way, |
| 38 | + # every Kangaroo that gets the default value get a |
| 39 | + # reference to a different list. |
| 40 | + |
| 41 | + # As a general rule, you should avoid using a mutable |
| 42 | + # object as a default value, unless you really know |
| 43 | + # what you are doing. |
| 44 | + if contents == None: |
| 45 | + contents = [] |
| 46 | + self.pouch_contents = contents |
| 47 | + |
| 48 | + def __str__(self): |
| 49 | + """return a string representation of this Kangaroo and |
| 50 | + the contents of the pouch, with one item per line""" |
| 51 | + t = [ object.__str__(self) + ' with pouch contents:' ] |
| 52 | + for obj in self.pouch_contents: |
| 53 | + s = ' ' + object.__str__(obj) |
| 54 | + t.append(s) |
| 55 | + return '\n'.join(t) |
| 56 | + |
| 57 | + def put_in_pouch(self, item): |
| 58 | + """add a new item to the pouch contents""" |
| 59 | + self.pouch_contents.append(item) |
| 60 | + |
| 61 | +kanga = Kangaroo() |
| 62 | +roo = Kangaroo() |
| 63 | +kanga.put_in_pouch('wallet') |
| 64 | +kanga.put_in_pouch('car keys') |
| 65 | +kanga.put_in_pouch(roo) |
| 66 | + |
| 67 | +print kanga |
| 68 | +print '' |
| 69 | + |
| 70 | +print roo |
0 commit comments