Created
February 12, 2016 14:54
-
-
Save BrandonLMorris/12c202a414b70c88a6be to your computer and use it in GitHub Desktop.
Demonstrating a gotcha of Python mutable types
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
""" | |
Simple demonstration of the gotcha that can occur in Python with mutable | |
types being shared across instances of a class | |
Taken with slight modification from the Python Guide | |
http://docs.python-guide.org/en/latest/writing/gotchas/ | |
(The same thing applies to default arguments) | |
""" | |
class Test(object): | |
lst = [] | |
def print_lst(self): | |
print(self.lst) | |
def add_to_lst(self, x): | |
self.lst.append(x) | |
class OtherTest(object): | |
def __init__(self, *args, **kwargs): | |
self.lst = [] | |
def print_lst(self): | |
print(self.lst) | |
def add_to_lst(self, x): | |
self.lst.append(x) | |
""" Program driver """ | |
if __name__ == '__main__': | |
test1, test2 = Test(), Test() | |
print('Appending 1, 2, and 3 to test1') | |
test1.add_to_lst(1); test1.add_to_lst(2); test1.add_to_lst(3) | |
print('test1.print_lst()') | |
test1.print_lst() | |
print() | |
print('test2.print_lst()') | |
test2.print_lst() | |
print() | |
print('As you can see, the list in test2 contained the same elements\n' | |
'as the list in test1 because they point to the same object\n' | |
'since they were defined at the class level\n') | |
print('Now we\'ll do the same thing with the OtherTest class, where\n' | |
'the list was defined in the __init__ method\n') | |
test1, test2 = OtherTest(), OtherTest() | |
print('Appending 1, 2, and 3 to test1') | |
test1.add_to_lst(1); test1.add_to_lst(2); test1.add_to_lst(3) | |
print('test1.print_lst()') | |
test1.print_lst() | |
print() | |
print('test2.print_lst()') | |
test2.print_lst() | |
print() | |
print('Now the two objects have two separate lists, independent of\n' | |
'each other') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment