Mutable class instance variables in Python act like they’re static
May 29, 2008 – 12:45 amThere’s a weird behavior in Python when dealing with Mutable types such as dictionaries, that when you modify a variable defined as a class attribute, you’re actually modifying a shared dictionary amongst all the classes. This seemed weird to me. You can read the lovely discussion about it, if you want. Or, just follow my code for a demo on how to deal with the issue. I just started Python on Monday night, so please overlook my n00bness.
## the first test will use an int, which is immutable.
class test1:
i = 0
def add(self):
self.i = self.i + 1
t = test1()
t.add()
t2 = test1()
t2.add()
t3 = test1()
t3.add()
## this will output 1, cool
print t3.i
## Lets try it again with a dictionary - which is a mutable type
class test2:
i = {} ## lets use a dictionary
def add(self, str):
self.i[str] = 1;
t = test2()
t.add('hi');
t.add('steve');
print t.i
# Will print the expected:
# {'steve': 1, 'hi': 1}
t2 = test2()
t2.add('bacon')
print t2.i
# But this prints:
# {'steve': 1, 'hi': 1, 'bacon': 1}
# Unexpected, in most languages
## it's necessary to define test2 in the following manner to avoid this weirdness
class test2:
def __init__(self):
self.i = {}
def add(self, str):
self.i[str] = 1;
t = test2()
t.add('hi');
t.add('steve');
print t.i
# Will print the expected:
# {'steve': 1, 'hi': 1}
t2 = test2()
t2.add('bacon')
print t2.i
# Will now print the expected:
# {'bacon': 1}
Reading the link above is a good idea if you’re interested to know why something works the way it does.


