-2

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Default values for arguments

I'm having trouble explaining how a list belonging to a class behaves.

>>> class A(object):
...     def __init__(self, L=[]):
...         self.L = L
...
>>> a1 = A()
>>> a2 = A()
>>> a1.L.append("test")
>>> print a1.L
['test']
>>> print a2.L
['test']

In this example, how did a2.L get a value in it? I only added an item to the list in a1. How is it that they're sharing the list now.

Thanks,

Henry

Community
  • 1
  • 1
ninhenzo64
  • 702
  • 1
  • 9
  • 23
  • 5
    This is so commonly asked - please see http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Jon Clements Jul 10 '12 at 20:06

1 Answers1

1

A brief summary of all the comments you will get:

The problem is nothing to do with the class. It's because you're storing the values in the default argument of a function, and default arguments are stored on the function objects.

Katriel
  • 120,462
  • 19
  • 136
  • 170