Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class attribute for two instances of the same class

Tags:

python

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?

like image 846
scdmb Avatar asked Dec 31 '11 12:12

scdmb


2 Answers

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]).

like image 140
hochl Avatar answered Sep 20 '22 00:09

hochl


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
like image 33
horejsek Avatar answered Sep 17 '22 00:09

horejsek