Class Variable Access and Assignment

Antoon Pardon apardon at forel.vub.ac.be
Thu Nov 3 07:50:51 EST 2005


Op 2005-11-03, Stefan Arentz schreef <stefan.arentz at gmail.com>:
> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>
> ...
>
>> >> No matter wat the OO model is, I don't think the following code
>> >> exhibits sane behaviour:
>> >> 
>> >> class A:
>> >>   a = 1
>> >> 
>> >> b = A()
>> >> b.a += 2
>> >> print b.a
>> >> print A.a
>> >> 
>> >> Which results in
>> >> 
>> >> 3
>> >> 1
>> >
>> > I find it confusing at first, but I do understand what happens :-)
>> 
>> I understand what happens too, that doesn't make it sane behaviour.
>> 
>> > But really, what should be done different here?
>> 
>> 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.

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.

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

> It doesn't touch the *class variable* A.a which is still 1.

But it accesses the class variable.

-- 
Antoon Pardon



More information about the Python-list mailing list