Class Variable Access and Assignment

Stefan Arentz stefan.arentz at gmail.com
Thu Nov 3 07:36:43 EST 2005


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.

> 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'. It doesn't touch the *class variable* A.a
which is still 1.

 S.



More information about the Python-list mailing list