Class Variable Access and Assignment

Stefan Arentz stefan.arentz at gmail.com
Thu Nov 3 08:55:31 EST 2005


Antoon Pardon <apardon at forel.vub.ac.be> writes:

> Op 2005-11-03, venk schreef <venkatasubramanian at gmail.com>:
> > You see,
> >      The seen behavior is due to the result of python's name
> > binding,scoping scheme.
> 
> I know what causes the behaviour. But I still think it is
> not sane behaviour.
> 
> 
> > ...
> >
> > the same thing happens in the case of b.a = b.a + 2 .... search for b.a
> > not found, read the value from the enclosing scope (of the class
> > object).... then assign b.a to the local scope, with the value 3.
> 
> This is an explanation depending on a specific implementation.
> 
> Now can you give me a language design argument that supports the 
> idea that in "b.a = b.a + 2" b.a refers to two different objects.
> 
> And even if you could do that, can you give such an argument that
> in "b.a += 2" that one occurence of b.a should refer to two different
> objects.

Your problem is a namespace conflict together with a certain
stubborness about lookup order :-)

It is really simple. When you say b.a then the instance variable 'a'
is looked up first. If it does not exist then a class variable lookup
is done.

Remember, Python is a dynamic language.

It is all according to how things have been in Python for a long time.

The real issue here is that you should propery name class variables so
that there can't be any confusion about class or instance scope. I use
all uppercase identifiers for class variables for example.

 S.



More information about the Python-list mailing list