Guest User

Untitled

a guest
Apr 21st, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. # Example showing how a subtlety in the way Python handles default
  2. # arguments can cause a bug.
  3.  
  4. class C(object):
  5. def __init__(self, list1=[], list2=None):
  6. # Wrong: if the list1 default argument of [] is used, that
  7. # default will be *shared* among all instances of the class.
  8. # If it is later modified, other instances can unexpectedly
  9. # inherit the modifications.
  10. self.list1 = list1
  11.  
  12. # With list2 we do things the right way
  13. if list2 is None:
  14. list2 = []
  15. self.list2 = list2
  16.  
  17. c1 = C()
  18. c1.list1.append('foo')
  19. c1.list1.append('bar')
  20.  
  21. c1.list2.append('peachy')
  22. c1.list2.append('keen')
  23.  
  24. c2 = C()
  25.  
  26. print c2.list1 # prints ['foo', 'bar']
  27. print c2.list2 # prints []
  28.  
  29. c2.list1.append('baz')
  30.  
  31. print c1.list1 # prints ['foo', 'bar', 'baz']
Add Comment
Please, Sign In to add comment