Search code examples
pythoninstances

Will adding an instance of a class to a list copy the instance or just 'reference' it?


allInstancesOfFoo = []

class foo(object):
    def __init__(self)
        allInstancesOfFoo.append(self)

bar1=foo()
bar2=foo()
bar3=foo()

Will doing this create copies of bars 1-3 and place them in that list, or will it simply add a 'reference' of sorts to them in that list. And, I know there are no C-style references in Python, but I can't think of a better word for it at the moment.

Also, sorry if this is a ridiculous question, I just want to make sure that doing this won't hog resources it doesn't need to.


Solution

  • In this case, your list will contain references to the original objects (bar1,bar2 and bar3) -- No copies will be made.

    For example:

    allInstancesOfFoo = []
    
    class foo(object):
        def __init__(self):
            allInstancesOfFoo.append(self)
    
    bar1=foo()
    bar2=foo()
    bar3=foo()
    print bar1 is allInstancesOfFoo[0]  #True
    

    As a side note, if you make a shallow copy of allInstancesOfFoo, that also only makes new references to existing objects:

    all_instances_of_foo = allInstancesOfFoo[:]
    print all(x is y for x,y in zip(all_instances_of_foo,allInstancesOfFoo))  #True