Suppose the following example:
class Example(object):
def __init__(self, data=[]):
self.data = data
If the data
argument is not given, the instance variable shall be initialized to the default value - an empty list. But consider the following session:
>>> e = Example()
>>> print(e.data)
[]
>>> e.data.append(1)
>>> print(e.data)
[1]
>>> e = Example()
>>> print(e.data)
[1]
First, an Example
instance is created without specifying the exact argument value, and thus the default is used. That's expected.
Then, the member variable is modified, and its state changes as expected.
Finally, a new instance of Example
is created again, the same way as in the first case. Yet, the contents of the member variable are different - the value of the variable somehow "survived" the creation of a new instance. Why?
Is this the expected behavior? What am I doing wrong?
This particular session was done in Python 2.7, but it works the same in Python 3.3.
Thanks, Petr