This question already has an answer here:
- How to avoid having class data shared among instances? 8 answers
I'm new to Python, with more of a Java background. I understand the concept of static class variables in Python, but it's come to my attention that lists and objects don't work the same way a string would, for example - they're shared between instances of a class.
In other words:
class box ():
name = ''
contents = []
def __init__ (self, name):
self.name = name
def store (self, junk):
self.contents.append(junk)
def open (self):
return self.contents
Now if I create two instances and try to add things to them:
a = box('Box A')
b = box('Box B')
a.store('apple')
b.store('berry')
print a.open()
print b.open()
Output:
['apple','berry']
['apple','berry']
It's very clear they're shared between the two instances of box.
Now I can get around it by doing the following:
def store (self, junk):
temp = self.contents
temp.append(junk)
self.contents = temp
But is there a cleaner/more conventional way? Can someone explain why this happens?