Class variable inheritance

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Sep 8 04:47:30 CEST 2009


On Mon, 07 Sep 2009 19:21:28 -0700, Henry 'Pi' James wrote:

> I've just found out that a subclass shares the class variables 

String variables are strings.

Int variables are ints.

Float variables are floats.

List variables are lists.

Class variables are classes. 

Classes are first-class objects in Python. Perhaps you mean class 
attributes?



> of its
> superclass until it's instantiated for the first time, but not any more
> afterwards:
...
> This makes no sense to me at all. Could it possibly be a bug?


You have misinterpreted what you have seen, and if there's a bug, it's in 
your code.

When you retrieve an attribute, Python first looks for instance 
attributes, then class attributes, then attributes attached to 
superclasses.

When you assign to an attribute, Python conceptually uses the exact same 
"search path", except that instance assignment always succeeds.

(Well, almost -- but if it fails, you get an exception.)

So in practice:

x = obj.whatever

may return the contents of an instance attribute "whatever", a class 
attribute, or an attribute of a superclass. But:

obj.whatever = x

always attempts to store x as an instance attribute, because there's no 
way for Python to read your mind and know that you mean a class attribute 
unless you say so explicitly. This attempt will either succeed, or it 
will raise an exception. Python doesn't try writing further along the 
hierarchy of instance/class/superclass(es).

If you wish to write to a class attribute, you have to explicitly say so:

obj.__class__.whatever = x


Your other misunderstanding relates to augmented assignment:

x += 1

does not modify x in place, it is *exactly* equivalent to:

x = x + 1

Given the rules of attribute access, obj.whatever += 1 is exactly 
equivalent to:

obj.whatever = obj.whatever + 1 

The right hand attribute access finds a class attribute, and the left 
hand one sets an instance attribute.


-- 
Steven



More information about the Python-list mailing list