There is this code:
class Sample:
variable = 2
object1 = Sample()
object2 = Sample()
print object1.variable # 2
print object2.variable # 2
object1.variable = 1
print object1.variable # 1
print object2.variable # 2 <- why not 1 too?
Why object2.variable is not also 1 after assignment to class variable?
Don’t confuse this with a static variable. In your case, both objects have a name
variablepoint to a2object after instantiation. Now if you change the variable to1in one object, all you do is bind thenameto a different object, i.e. the1object. The name in object2 still refers to a2object. The original class object is untouched and still has the namevariablepoint to a2, soobject3 = Sample()will have a2bound tovariableas well.One way to get around this is to write the class like the following:
This is because all classes bind the name
variableto the same, muatable object, and you manipulate the contents of this same object (variable[0]).