Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96169
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
"""
15
16
WARNING: this program contains a NASTY bug. I put
17
it there on purpose as a debugging exercise, but
18
you DO NOT want to emulate this example!
19
20
"""
21
22
class Kangaroo:
23
"""A Kangaroo is a marsupial."""
24
25
def __init__(self, name, contents=[]):
26
"""Initialize the pouch contents.
27
28
name: string
29
contents: initial pouch contents.
30
"""
31
# The problem is the default value for contents.
32
# Default values get evaluated ONCE, when the function
33
# is defined; they don't get evaluated again when the
34
# function is called.
35
36
# In this case that means that when __init__ is defined,
37
# [] gets evaluated and contents gets a reference to
38
# an empty list.
39
40
# After that, every Kangaroo that gets the default
41
# value gets a reference to THE SAME list. If any
42
# Kangaroo modifies this shared list, they all see
43
# the change.
44
45
# The next version of __init__ shows an idiomatic way
46
# to avoid this problem.
47
self.name = name
48
self.pouch_contents = contents
49
50
def __init__(self, name, contents=None):
51
"""Initialize the pouch contents.
52
53
name: string
54
contents: initial pouch contents.
55
"""
56
# In this version, the default value is None. When
57
# __init__ runs, it checks the value of contents and,
58
# if necessary, creates a new empty list. That way,
59
# every Kangaroo that gets the default value gets a
60
# reference to a different list.
61
62
# As a general rule, you should avoid using a mutable
63
# object as a default value, unless you really know
64
# what you are doing.
65
self.name = name
66
if contents == None:
67
contents = []
68
self.pouch_contents = contents
69
70
def __str__(self):
71
"""Return a string representaion of this Kangaroo.
72
"""
73
t = [ self.name + ' has pouch contents:' ]
74
for obj in self.pouch_contents:
75
s = ' ' + object.__str__(obj)
76
t.append(s)
77
return '\n'.join(t)
78
79
def put_in_pouch(self, item):
80
"""Adds a new item to the pouch contents.
81
82
item: object to be added
83
"""
84
self.pouch_contents.append(item)
85
86
87
kanga = Kangaroo('Kanga')
88
roo = Kangaroo('Roo')
89
kanga.put_in_pouch('wallet')
90
kanga.put_in_pouch('car keys')
91
kanga.put_in_pouch(roo)
92
93
print(kanga)
94
print(roo)
95
96
# If you run this program as is, it seems to work.
97
# To see the problem, trying printing roo.
98
99