Class Variable Access and Assignment

Antoon Pardon apardon at forel.vub.ac.be
Thu Nov 3 16:02:24 CET 2005


Op 2005-11-03, Stefan Arentz schreef <stefan.arentz at gmail.com>:
> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>
> ...
>
>> Fine, we have the code:
>> 
>>   b.a += 2
>> 
>> We found the class variable, because there is no instance variable,
>> then why is the class variable not incremented by two now?
>
> Because it really is executed as:
>
>  b.a = b.a + 2

That is an explanation, not a reason. 

>   1. get 't'b.a and store it in a temporary 't' (found the instance)
>   2. add 2 to 't'
>   3. store 't' in 'b.a'
>
> The last operation stores it into an instance variable.

[ I think you mean '(found the class variable)' in line 1 ]

All you are doing here is explain how the current implemantation treats
this. You are not giving arguments for why the result of this
implementation should be considered sane behaviour.

>> > Remember, Python is a dynamic language.
>> 
>> So? Python being a dynamic language doesn't prevent the following to fail:
>> 
>> >>> a=1
>> >>> def f():
>> ...   a += 2
>> ... 
>> >>> f()
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>>   File "<stdin>", line 2, in f
>> UnboundLocalError: local variable 'a' referenced before assignment
>
> See the 'global' keyword.

You missed the point. If python being a dynamic language would be the
answer to the interaction between instance and class variable, why
then is the interaction between local and global variable different,
why wouldn't the f code be executed as follows

  1. get a and store in in a temporary 't' (found the global)
  2. add 2 to 't'
  3. store 't' in 'a'

The last operation storing it in f's local namespace.

-- 
Antoon Pardon



More information about the Python-list mailing list