Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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']
Add Comment
Please, Sign In to add comment