I have an issue in Python I couldn’t believe to find out. See the following code:
class Container(object):
array = []
def __init__(self):
print self.array
for i in range(0, 5):
container = Container()
container.array.append('Test')
print 'Last Container:', container.array
The output is:
[]
['Test']
['Test', 'Test']
['Test', 'Test', 'Test']
['Test', 'Test', 'Test', 'Test']
Last Container: ['Test', 'Test', 'Test', 'Test', 'Test']
I thought the Container class is initialized with the values at the top on instantiation. Why is this not the case?
Thank you!
Any attributes that you place directly inside of the class definition are class attributes, so
Container.arrayis shared among all instances ofContainer.If you want an instance attribute instead, set
self.array = []inside of__init__():