Class Variable Access and Assignment

Steven D'Aprano steve at
Thu Nov 3 16:00:52 CET 2005

On Thu, 03 Nov 2005 12:50:51 +0000, Antoon Pardon wrote:

>>> I don't care what should be different. But a line with only one
>>> referent to an object in it, shouldn't be referring to two different
>>> objects.
>> It doesn't.
> Yes it does. If the b.a refers to the instance variable, then an
> AttributeError should be raised, because the instance variable doesn't
> exist yet, so you can't add two to it.

Then you don't approve of inheritance? That's fine, it is your choice, but
as far as I know, all OO languages include inheritance. I can't imagine
why you would want this to happen:

py> class BetterList(list):
...     def wobble(self):
...         """Wobble a list."""
...         pass
py> L = BetterList((1, 2, 3))
py> L.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'BetterList' object has no attribute 'sort'

(It just goes to show that Explicit is better than Implicit is not
*always* true.)

> If the b.a refers to the class variable then two should be added to it.
> Neither happens instead we get some hybrid in which an instance varible
> is created that gets the value of class variable incrented by two.

Which is precisely the expected behaviour. First you fetch the instance
attribute, which by the rules of inheritance falls back to the value
of the class attribute if it doesn't yet exist (which, in this specific
case, it does not). Then you add two to it, and store the result in the
instance attribute. You can't increment the object 1 because it is

>>> In the line: b.a += 2, the b.a should be refering to the class
>>> variable or the object variable but not both. So either it could raise
>>> an attribute error or add two to the class variable.
>> It does exactly what you say. It adds 2 to the a *instance variable* of
>> the object instance in 'b'.
> There is no instance variable at that point. How can it add 2, to
> something that doesn't exist at the moment.

By the standard rules of inheritance.


More information about the Python-list mailing list