Created
December 1, 2009 18:24
-
-
Save natesilva/246507 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example showing how a subtlety in the way Python handles default | |
# arguments can cause a bug. | |
class C(object): | |
def __init__(self, list1=[], list2=None): | |
# Wrong: if the list1 default argument of [] is used, that | |
# default will be *shared* among all instances of the class. | |
# If it is later modified, other instances can unexpectedly | |
# inherit the modifications. | |
self.list1 = list1 | |
# With list2 we do things the right way | |
if list2 is None: | |
list2 = [] | |
self.list2 = list2 | |
c1 = C() | |
c1.list1.append('foo') | |
c1.list1.append('bar') | |
c1.list2.append('peachy') | |
c1.list2.append('keen') | |
c2 = C() | |
print c2.list1 # prints ['foo', 'bar'] | |
print c2.list2 # prints [] | |
c2.list1.append('baz') | |
print c1.list1 # prints ['foo', 'bar', 'baz'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment