Class Variable Access and Assignment

Graham graham.abbott at gmail.com
Thu Nov 3 04:43:40 EST 2005


This has to do with class variables and instances variables.

Given the following:

<code>

    class _class:
        var = 0
        #rest of the class

    instance_b = _class()

    _class.var=5

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

</code>

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:

<code>

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

</code>

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.


Graham




More information about the Python-list mailing list