Search code examples
pythoninstance-variablesclass-variablescanopy

Instance variable of type list behaves as class variable


In the following code, I thought list wouldbe a unique variable to each object constructed. Why is it shared as a class variable?

01 class Thing(object):
02     def __init__(self, my_list=[]): 
03         self.list = my_list 
04         return 
05 
06 thing1=Thing()
07 thing2=Thing()
08 thing1.list.append(1)
09 print thing2.list     

id(thing1) is distinct from id(things2) but id(thing1.list) is the same as id(thing2.list).

If I use self.list = [] on line 3, the attribute is unique to each Thing. If I use thing1 = Thing(my_list=[]) on line 6, and similarly on line 7, then the attribute is unique to each Thing.

I am running Python 2.7 within the Canopy environment.


Solution

  • You should be doing something like this:

    01 class Thing(object):
    02     def __init__(self, my_list=None):
    03         if my_list is None:
    04           my_list = []
    04         self.list = my_list 
    

    See this post for an explanation as to why keyword arguments behave this way.