Created
February 12, 2016 14:54
-
-
Save BrandonLMorris/12c202a414b70c88a6be to your computer and use it in GitHub Desktop.
Revisions
-
BrandonLMorris created this gist
Feb 12, 2016 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,69 @@ """ 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')