AllenDowney / ThinkPython2

LaTeX source and supporting code for Think Python, 2nd edition, by Allen Downey.
Other
2.49k stars 1.65k forks source link

exercise 17.2: GoodKangaroo.py has its own pitfall #100

Open jgmbenoit opened 2 years ago

jgmbenoit commented 2 years ago

The suggested solution has a pitfall that somehow reproduces the same issue. If we use the same content to initialize kanga and roo, then a new content put in one of them also appears in the other one. More specifically, if we replace

kanga = Kangaroo('Kanga')
roo = Kangaroo('Roo')

by

prepouch=['red','green','blue']
kanga = Kangaroo('Kanga',precontents)
roo = Kangaroo('Roo',precontents)

then the output becomes

Kanga has pouch contents:
    'red'
    'green'
    'blue'
    'wallet'
    'car keys'
    <__main__.Kangaroo object at 0x7f2b4c049e20>
Roo has pouch contents:
    'red'
    'green'
    'blue'
    'wallet'
    'car keys'
    <__main__.Kangaroo object at 0x7f2b4c049e20>

while we may expect

Kanga has pouch contents:
    'red'
    'green'
    'blue'
    'wallet'
    'car keys'
    <__main__.Kangaroo object at 0x7f0abfdc4d30>
Roo has pouch contents:
    'red'
    'green'
    'blue'

I obtained the last output by assigning a copy of contents:

self.pouch_contents = contents[:]