This question already has an answer here:
- How to avoid having class data shared among instances? 8 answers
I don't understand the difference in the following example. One time an instance of a class can CHANGE the class variable of another instance and the other time it can't?
Example 1:
class MyClass(object):
mylist = []
def add(self):
self.mylist.append(1)
x = MyClass()
y = MyClass()
x.add()
print "x's mylist: ",x.mylist
print "y's mylist: ",y.mylist
Output:
x's mylist: [1]
y's mylist: [1]
So here an instance x
of class A
was able to access and modify the class attribute mylist
which is also an attribute of the instance y
of A
.
Example 2:
class MyBank(object):
crisis = False
def bankrupt(self) :
self.crisis = True
bankX = MyBank()
bankY = MyBank()
bankX.bankrupt()
print "bankX's crisis: ",bankX.crisis
print "bankY's crisis: ",bankY.crisis
bankX's crisis: True
bankY's crisis: False
Why does this not work in this example?