I have the following Python code:
#!/usr/bin/env python2.6
class container(object):
name = 'container'
configuration = {'var1': 'var1',
'var2': 'var2'}
if __name__ == "__main__":
container1 = container()
container2 = container()
container2.name = 'container2'
container2.configuration['var2'] = 'newvar2'
print container1.name
print container1.configuration['var2']
I expect this to print ‘container’ and ‘var2’, but for the latter it prints ‘newvar2’ instead
Why does the configuration variable point to the same dictionary for both objects? How can I fix this?
Most answers are already explaining that name and configuration are class variables. Why does the change of container2.name not influence container1.name?
Because
configurationis a class variable and not an instance variable. Fixing this should fix your problem.What’s going on here is that
configurationends up living incontainter.__dict__instead of in the dictionaries of its instances when you make it a class variable. This means thatc.configurationis just accessingcontainer.__dict__['configuration']for all instancesc.For any class variable, an assignment of the form
c.foo = x, creates an entry forfooinc.__dict__which shadows its entry incontainer.__dict__. So a lookup will return that first. If you delete it, then a lookup will go back to retrieving the class instance. You could doand then
c.configurationwould be whateverxwas. But inserting a key isn’t an assignment, it’s a method call on an existing object accessed through an existing binding.You could get away with making
namea class variable but if you want it to change from one instance to another then it should be an instance variable (unless you want a class wide default of course).so:
=,setattror directly inserting in__dict__) on an instance will shadow a class variable. The class variable is still there.