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 variable point to a 2 object after instantiation. Now if you change the variable to 1 in one object, all you do is bind the name to a different object, i.e. the 1 object. The name in object2 still refers to a 2 object. The original class object is untouched and still has the name variable point to a 2, so object3 = Sample() will have a 2 bound to variable as well.
One way to get around this is to write the class like the following:
>>> class Sample:
...     variable=[2]
... 
>>> object1 = Sample()
>>> object2 = Sample()
>>> print object1.variable[0]; print object2.variable[0]
2
2
>>> object1.variable[0]=1
>>> print object1.variable[0]; print object2.variable[0]
1
1
This is because all classes bind the name variable to the same, muatable object, and you manipulate the contents of this same object (variable[0]).
Because you assign new instance variable into instance, not class variable. If you can change class attribute, then you must set variable through __class__ attribute. (Or directly to class object.)
class Sample:
    variable = 2
object1 = Sample()
object2 = Sample()
print object1.variable  # 2
print object2.variable  # 2
object1.__class__.variable = 1 # or Sample.variable = 1
print object1.variable  # 1
print object2.variable  # 1
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With