Class Variable Access and Assignment

Graham at
Thu Nov 3 10:43:32 CET 2005

This has to do with class variables and instances variables.

Given the following:


    class _class:
        var = 0
        #rest of the class

    instance_b = _class()


    print instance_b.var # -> 5
    print _class.var # -> 5


Initially this seems to make sense, note the difference between to last
two lines, one is refering to the class variable 'var' via the class
while the other  refers to it via an instance.

However if one attempts the following:


    instance_b.var = 1000 # -> _class.var = 5
    _class.var = 9999 # -> _class.var = 9999


An obvious error occurs. When attempting to assign the class variable
via the instance it instead creates a new entry in that instance's
__dict__ and gives it the value. While this is allowed because of
pythons ability to dynamically add attributes to a instance however it
seems incorrect to have different behavior for different operations.

There are two possible fixes, either by prohibiting instance variables
with the same name as class variables, which would allow any reference
to an instance of the class assign/read the value of the variable. Or
to only allow class variables to be accessed via the class name itself.

Many thanks to elpargo and coke. elpargo assisted in fleshing out the
best way to present this.

perhaps this was intended, i was just wondering if anyone else had
noticed it, and if so what form would you consider to be 'proper'
either referring to class variables via the class itself or via
instances of that class. Any response would be greatly appreciated.


More information about the Python-list mailing list